Swift 内部类可以访问外部类的 self 吗? [英] Do Swift inner classes have access to self of outer class?

查看:38
本文介绍了Swift 内部类可以访问外部类的 self 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Java 背景,当您声明内部类时,它要么是静态的,并且无法访问外部类的实例,要么不是静态的,并且可以访问外部类的实例正在操作的类.参见 http://en.wikipedia.org/wiki/Inner_class#Types_of_nested_classes_in_Java

I'm coming from a Java background where when you declare the inner class, it's either static, and doesn't have access to the instance of the outer class, or it's not static, and can access the instance of the outer class that's being operated on. See http://en.wikipedia.org/wiki/Inner_class#Types_of_nested_classes_in_Java

Swift 有这个概念吗?从我的测试来看,我似乎无法访问 Outerself 对象,但我肯定可能做错了什么.

Does Swift have any concept of this? From my testing, I cannot seem to get access to the Outer's self object, but I definitely could be doing something wrong.

class Outer {
    let value = ""
    class Inner {
        func foo() {
            let bar = value // 'Outer.Type' does not have a member named 'value'
        }
    }
}

推荐答案

AFAIK,您无法开箱即用地访问外部类.

AFAIK, you can't access the outer class out-of-the-box.

但是你能做的是:

class Outer {

    let value = ""
    var inner = Inner()

    class Inner {

        weak var parent: Outer! = nil

        func foo() {
            let bar = parent.value
        }

    }

    init() {
        inner.parent = self
    }

}

或者:

class Outer {

    class Inner {

        unowned let parent: Outer

        init(parent: Outer) {
            self.parent = parent
        }

    }

    let value = ""
    var inner: Inner! = nil

    init() {
        inner = Inner(parent: self)
    }

}

这篇关于Swift 内部类可以访问外部类的 self 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆