Using KVO in Swift by third party controls (Observable-Swift)


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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,599评论 5 6
  • 人们总说时间会改变一切,但实际上你必须自己去改变一切 这辈子最对不起的就是自己的心了,让它疼了一次又一次。 千万个...
    青蛙王阅读 1,652评论 0 0
  • NSThread 实现多线程的技术方案之一. 面向对象的开发思想. 每个对象表示一条线程. 创建线程三种方式 准备...
    月下独酌灬阅读 11,364评论 1 10
  • 早上打电话 你:喂 ?醒了吗? 我:嗯 你:家里今天冷吧?多穿点衣服! 我:嗯,马上起。 你:那快起来吧,不要迟到...
    闲暇的小时光阅读 1,562评论 0 1
  • 却还是控制不住的想码字来宽慰内心的沉重。 我还是那只蝼蚁吧! 渴望着惊叹着蚍蜉撼树的震撼与光芒却忘了渺小希望背后的...
    一只想变瘦的猫阅读 2,548评论 0 0

友情链接更多精彩内容