When should I access properties with self in swift?

后端 未结 6 2035
一生所求
一生所求 2020-11-27 04:38

In a simple example like this, I can omit self for referencing backgroundLayer because it\'s unambiguous which backgroundLayer the backgroundColor is set on.



        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 05:24

    Looking at Ray Wenderlich's style guide

    Use of Self

    For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

    Use self only when required by the compiler (in @escaping closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without self then omit it.

    Swift documentation makes the same recommendation.

    The self Property

    Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

    The increment() method in the example above could have been written like this:

    func increment() {
        self.count += 1
    }
    

    In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.

    The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

    Here, self disambiguates between a method parameter called x and an instance property that is also called x:

    struct Point {
        var x = 0.0, y = 0.0
    
        func isToTheRightOf(x: Double) -> Bool {
            return self.x > x
        }
    }
    
    let somePoint = Point(x: 4.0, y: 5.0)
    if somePoint.isToTheRightOf(x: 1.0) {
        print("This point is to the right of the line where x == 1.0")
    }
    
    // Prints "This point is to the right of the line where x == 1.0"
    

提交回复
热议问题