美文网首页
Using KVO in Swift by third part

Using KVO in Swift by third part

作者: TomatosX | 来源:发表于2016-07-10 20:50 被阅读15次

Using KVO in swift is a very troublesome thing. But Observable-Swift control can make us use elegant KVO in swift.
Now, let's look at how to use Observable-Swift

A simple example:

var str = Observable("Hello ")
        
str.afterChange += {
    print("before value: \($0), after value: \($1)")
}

str <- "ABC"
str.value += "World"
str ^= "EFG"

The output results are as follows:

before value: Hello , after value: ABC

before value: ABC, after value: ABCWorld

before value: ABCWorld, after value: EFG

We can see the "<-" and "^=" operation is the same. Replace the value of the variable.
We can use the Value property to access the value of the Observable type. So, str.value += "World" means add value to variable.

Next, let's us look at a example of struct type:

struct Person {
    let first: String
    var last: Observable<String>

    init(first: String, last: String) {
        self.first = first
        self.last = Observable(last)
    }
}

var ramsay = Person(first: "Ramsay", last: "Snow")
ramsay.last.afterChange += { println("Ramsay \($0) is now Ramsay \($1)") }        
ramsay.last <- "Bolton"

Ramsay Snow is now Ramsay Bolton

Remember, the afterChange method must be written in front of the ramsay.last <- "Bolton".

Please refer to the official document for more usage.

相关文章

网友评论

      本文标题:Using KVO in Swift by third part

      本文链接:https://www.haomeiwen.com/subject/ahbdjttx.html