The Rules for Nesting Objects in Swift
Image via Author

The Rules for Nesting Objects in Swift


When an object type is declared inside another object type, it forms a nested type.


class Car {
    
    struct Engine {
        static let startEngine = "vroom vroom"
    }
    
    func drive() {
        print(Car.Engine.startEngine)
    }
}

var myCar = Car()
myCar.drive() // vroom vroom        

In this code, the Car class has a struct and method, named Engine and drive( ) respectively.

The struct has a static property of type String, with the value of “vroom vroom.” The drive( ) method accesses the value of the static property through a dot notation and prints it out.

Then an instance of the Car is created and the result is assigned to the variable named myCar.

Calling .drive( ) on the instance prints out “vroom vroom.

For the drive( ) method to access the static property it had to go through the Car class and Engine struct via the dot notation.

This is because the rules for referring to it are different. The surrounding object behaves much like a namespace and must be explicitly referenced to access the nested object type.



Car.Engine.startEngine        

In the example shown, the Engine struct is a namespace inside the Car class.

Another thing to note about nested types is that they can access the surrounding type’s static / class members, but the same is not true for the instance members.



class Van {
    
    static let startEngine = "vroom vroom"
    
    struct AmbulanceNoise {
        static let ambulanceVan = "weeeeoooooo"
        func driveAmbulance() {
            drive() // error: Instance member 'drive' of type 'Van' cannot be used on instance of nested type 'Van.AmbulanceNoise'
        }
        var startAmbulanceEngin = startEngine
    }
    
    func drive() {
        print(Van.AmbulanceNoise.ambulanceVan)
    }
}

var ambulance = Van()
ambulance.drive()        

Here, the code inside the AmbulanceNoise struct cannot refer to the instance method drive( ) but can directly refer to the static property startEngine without explicit namepsacing.


This is because only instances of Car have access to its instance members.

要查看或添加评论,请登录

Ijeoma Nelson的更多文章

社区洞察

其他会员也浏览了