Swift nested class properties

Swift’s nested classes are not like Java’s nested classes. Well, they’re like one kind of Java’s nested classes, but not the kind you’re thinking of.

In Java, an instance of an inner class automatically has a reference to an instance of the outer class (unless the inner class is declared static). You can only create an instance of the inner class if you have an instance of the outer class. That’s why in Java you say something like this.new nested().

In Swift, an instance of an inner class is independent of any instance of the outer class. It is as if all inner classes in Swift are declared using Java’s static. If you want the instance of the inner class to have a reference to an instance of the outer class, you must make it explicit:

class Master {
    var test = 2;

    class Nested{
        init(master: Master) {
            let example = master.test;
        }
    }

    func f() {
        // Nested is in scope in the body of Master, so this works:
        let n = Nested(master: self)
    }
}

var m = Master()
// Outside Master, you must qualify the name of the inner class:
var n = Master.Nested(master:m)

// This doesn't work because Nested isn't an instance property or function:
var n2 = m.Nested()

// This doesn't work because Nested isn't in scope here:
var n3 = Nested(master: m)

Leave a Comment