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
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' } } }
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.
Inner Class You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class.
AFAIK, you can't access the outer class out-of-the-box.
But what you can do is:
class Outer { let value = "" var inner = Inner() class Inner { weak var parent: Outer! = nil func foo() { let bar = parent.value } } init() { inner.parent = self } }
Or:
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) } }
Nested types don't have any special access to the types that contain them. But I don't think that's all that's going on here. You seem to be a little fuzzy on classes versus instances.
value
is a property of the Outer class. That means each instance of Outer has its own value
. Inner is a separate class that exists in the namespace of Outer. So when you write let bar = value
, there is no such thing as value
to access, because that only exists in instances of Outer, and we don't have any instances at hand. If it were a class property, you could do let bar = Outer.value
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With