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

前端 未结 3 1347
囚心锁ツ
囚心锁ツ 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:27

    A static var is property variable on a struct versus an instance of the struct. Note that static var can exist for an enum too.

    Example:

    struct MyStruct {
        static var foo:Int = 0
        var bar:Int
    }
    
    println("MyStruct.foo = \(MyStruct.foo)") // Prints out 0
    
    MyStruct.foo = 10
    
    println("MyStruct.foo = \(MyStruct.foo)") // Prints out 10
    
    var myStructInstance = MyStruct(bar:12)
    
    // bar is not 
    // println("MyStruct.bar = \(MyStruct.bar)")
    
    println("myStructInstance = \(myStructInstance.bar)") // Prints out 12
    

    Notice the difference? bar is defined on an instance of the struct. Whereas foo is defined on the struct itself.

提交回复
热议问题