Swift类中如何创建一个对外只读对内可读写的属性

来源:互联网 发布:淘宝查优惠券插件 编辑:程序博客网 时间:2024/05/29 15:20

很简单用private修饰符,后面跟限制关键字set:

class Day{    private(set) var rawValue:Int = 0    func showRawValue(){        print("raw is \(rawValue)")    }    func forwardRawValue(){        rawValue += 1    }}

不过如上上述类定义在playground中的话,实际你会发现如果去掉后面的(set)照样可以在外部访问:

let day = Day()day.rawValue+=1 //that's OK!day.forwardRawValue()day.showRawValue()

这是因为Swift中private修饰符的含义和传统面向对象中的不太一样,在Swift中private只是限制在同一个文件中的可见性.所以要想它真正发挥作用,你必须在外部文件中才能体会到:

class ViewController: UIViewController {    func test(){        let day = Day()        //day.rawValue = 99 Error!!!        day.showRawValue()        day.forwardRawValue()        day.showRawValue()    }}

That’s OK! ;]

1 0
原创粉丝点击