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.
网友评论