我来自Java背景,当您声明内部类时,它是静态的,不能访问外部类的实例,或者它不是静态的,并且可以访问正在被访问的外部类的实例。进行操作。参见http://en.wikipedia.org/wiki/Inner_class#Types_of_nested_classes_in_Java
斯威夫特对此有什么概念吗?从测试中,我似乎无法访问Outer的self对象,但是我肯定做错了。
Outer
self
class Outer { let value = "" class Inner { func foo() { let bar = value // 'Outer.Type' does not have a member named 'value' } } }
AFAIK,您不能开箱即用地访问外部类。
但是您可以做的是:
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) } }