Differences between “static var” and “var” in Swift

前端 未结 3 1330
囚心锁ツ
囚心锁ツ 2021-01-02 04:54

What is the main difference between \"static var\" and \"var\" in Swift? Can someone explain this difference to me, possibly with a little example?

3条回答
  •  孤街浪徒
    2021-01-02 05:20

    static var belongs to type itself while var belongs to instance (specific value that is of specific type) of type. For example:

    struct Car {
        static var numberOfWheels = 4
        var plateNumber: String
    }
    
    Car.numberOfWheels = 3
    let myCar = Car(plateNumber: "123456")
    

    All cars has same amount of wheels. An you change it on type Car itself.

    In order to change plate number you need to have instance of Car. For example, myCar.

提交回复
热议问题