swfit 的 get 和 set 方法, willSet 和 didSet

struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
          let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}


set 参数名直接才括号指定就行


如果不指定参数名,默认名称为newValue

“struct AlternativeRect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}”

摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks. https://itun.es/au/jEUH0.l


“class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}”

摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks. https://itun.es/au/jEUH0.l

 willSet 可以设置参数名,didSet 默认oldValue, 
  

至于in-out Parameter

定义:

 1.When the function is called, the value of the argument is copied.

 2.In the body of the function, the copy is modified.

 3.When the function returns, the copy’s value is assigned to the original argument.

“var x = 10 var y = 20
func f(a: inout Int, b: inout Int) {
    a += 1
    b += 10
}
f(a: &x, b: &y)”

摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks. https://itun.es/au/jEUH0.l

其实就是传引用,如果类的这个属性作为一个函数的inout类型参数传递,那么它的get 和set方法会经常被调用。 

至于这种In-out 参数的具体作用,现在没有具体的体会,以后再说.

今天查了一下,其实也就是修改原值

在siwft中,除了class是默认引用传递外,其他数据类型如float,struct等等都属于值传递。

所以要对非class 类型进行改变,那么要使用inout 类型

 
 

你可能感兴趣的:(收获和安排)