观察员迅速

时间:2016-12-22 10:31:12

标签: swift readonly observers

创建一个Triangle类并使用一个名为isEquilateral的只读计算属性,它将确定是否像这样相等

    class Triangle {
    var a: Int
    var b: Int
    var c: Int
    // initialization stuff
    var isEquilateral: Bool {
    return (sideA, sideB) == (sideB, sideC)
    }
}

如何添加一个观察者来检查长度是否发生变化,比如说一个不同类型的三角形?我是否将它添加到计算属性(isEquilateral)或外部?

3 个答案:

答案 0 :(得分:1)

this教程中所述:

在你的情况下:

var a: Int {
    willSet {
        // First time set
    }
    didSet {
        // Value changed
    }
}
var b: Int ...
var c: Int ...

这种方法适合我几次

答案 1 :(得分:1)

您正在寻找

Property Observer

  

财产观察员观察并回应房产的变化   值。每次物业的价值都会调用物业观察员   设置,即使新值与属性的当前值相同   值。

因此,假设您要观察UPDATE secondfile SET status = 'Added' WHERE NOT EXITS( select 1 from firstfile where Emplid= secondfile.Emplid ) 属性的更改,可以将其实现为:

a

致电(追踪):

class Triangle {
    var a: Int? {
        willSet {
            print("the new value is about to be: \(newValue)")
        }
        didSet {
            print("the old value was: \(oldValue)")
        }
    }

    var b: Int?
    var c: Int?

    // initialization stuff

    // ...
}

正如您所看到的,它会让您知道let myTriangle = Triangle() myTriangle.a = 10 // this will print: // the new value is about to be: Optional(10) // the old value was: nil (nil because it's optional...) // re-assign a new value: myTriangle.a = 20 // this will print: // the new value is about to be: Optional(20) // the old value was: Optional(10) 的值已经更改,它还会告诉您新旧值是什么。

因此,通过实现作为属性观察者,您可以在更改a属性的值时添加自定义行为;让我们说 - 例如 - 如果a发生变化,您希望c等于a的新值:

var a: Int? {
        willSet {
            print("the new value is about to be: \(newValue)")
            b = newValue
        }
        didSet {
            print("the old value was: \(oldValue)")
        }
    }

或者 - 另一个示例 - 您希望在更改a的值时调用函数来执行某些操作:

var a: Int? {
    willSet {
        print("the new value is about to be: \(newValue)")
        doSomething()
    }
    didSet {
        print("the old value was: \(oldValue)")
    }
}

private func doSomething() {
    print("doing something...")
}

有关详细信息,建议您查看Apple Documentation - “Property Observers”部分。

希望它有所帮助。

答案 2 :(得分:0)

如果您想跟踪课外的变化,可以使用通知中心。例如:

class Triangle {
var a: Int {
    didSet {
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "aValueChanged"), object: self))
    }
}

func randomFunc() {
    a = 20
}
}

抓住这些通知:

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.someFunc), name: NSNotification.Name(rawValue: "aValueChanged"), object: nil)
triangle.something()

接收通知的方法:

func someFunc(notification: Notification) {
    let triangle = notification.object as! Triangle
    print("a value to \(triangle.a)")
}

这将允许您检查班级之外的更改。输出将为a value changed to 20