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 类型


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值