When to use static constant and variable in Swift?

后端 未结 4 1672
刺人心
刺人心 2020-12-07 13:16

There are some posts for how to write code for static constant and static variable in Swift. But it is not clear when to use static constant<

4条回答
  •  Happy的楠姐
    2020-12-07 13:48

    This is more of an important comment:

    class Person {
        static var name = "Static John" // a property of Person 'type'
        var name = "Alex" // a property of Person 'instance'
    
        var nonStaticName = "Peter"
        static var staticName = "Sara"
    
    
    
        static func statFunc() {
            let x = Person.name // Static John
            let y = name // Static John or Alex?!  Static John!!!!
            let r = staticName // Sara
            let k = nonStaticName // ERROR: instance member 'nonStaticName' cannot be used on type 'Person'
            // The compiler is like: I'm referring to the `nonStaticName` property of which instance?! There is no instance! Sorry can't do!
    
        }
    
        func nonStaticFunc() {
            let x = Person.name // Static John
            let y = name // Static John or Alex?! Alex!!! Because we're in a instance scope...
            let k = nonStaticName // Obviously works
            let r = staticName // ERROR: static member 'staticName' cannot be used on instance of type 'Person'. Person.staticName will work
        }
    }
    

    Interesting observations:

    First:

    static var name = "Static John" // a property of Person 'type'
    var name = "Alex" // a property of Person 'instance'
    

    creates no conflicts.

    Second:

    You can't ever use instance variables inside static variables. You can use static variables inside instance functions if you refer to it by prefixing it with the type ie do Person.name, whereas

    static variables can be accessed inside static functions with or without prefixing the type ie Person.staticName or staticName both work.

提交回复
热议问题