scala模仿swift的属性观察器

使用swift开发ios的时候把业务可以写入到属性观察器,我也挺喜欢叫钩子函数


    var currentIndex:Int?{
        didSet{
            if currentIndex != 3{
                titleViewCells![currentIndex!].focusCell()
                titleViewCells!.filter{$0.data?.index != currentIndex}.forEach{$0.blurCell()}
                if let scrollview = scrollerContainer {
                    //滚动,切换子控制器
                    var offset = scrollview.contentOffset
                    offset.x = CGFloat(currentIndex!) * scrollview.width
                    scrollview.setContentOffset(offset, animated: true)
                }
            }else{
               forwardPage()
            }
        }
    }

currentIndex是子控制器容器的索引,他的更新会引起子控制器的切换,其实这个实现完全可以在属性setter函数重写(重载也可以)

class People(name:String,about:String){
    type  observer = (Int) => Unit
    private var privateAge = 0
    def age = {privateAge}
    def age_(willSet:observer=(newage:Int)=>{println(s"willSet ${newage}")},
             newValue: Int,
             didSet:observer=(newage:Int)=>{println(s"didSet ${newage}")}):Unit= {
                willSet(newValue);
                privateAge = newValue
                didSet(newValue);
    }
}
object KVOObject{
    def main(args: Array[String]): Unit = {
        val p = new People("twp","programer")
            p.age_(
                (newage:Int)=>{
                        println(s"newage is ${newage} and willSet")
                        println(s"age oldval is ${p.age}")
                    },
                26,
                (newage:Int)=>{
                    println(s"newage is ${newage} and didSet")
                    println(s"age  is ${p.age}")
                })
        p.age_(newValue = 26) }
}

这来实现组装的回调来编写业务处理还是很方便的。(第一次写简书,多多见谅)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • __block和__weak修饰符的区别其实是挺明显的:1.__block不管是ARC还是MRC模式下都可以使用,...
    LZM轮回阅读 3,364评论 0 6
  • ———————————————回答好下面的足够了---------------------------------...
    恒爱DE问候阅读 1,759评论 0 4
  • 史上最全的iOS面试题及答案 iOS面试小贴士———————————————回答好下面的足够了----------...
    Style_伟阅读 2,430评论 0 35
  • 软件工程专业出身的自心经老师,一直对互联网公司的发展颇为关注,尤其对其爆发式崛起背后的风水成因痴迷不已。 之前,我...
    自心经阅读 1,449评论 0 0