Information Hiding the “Swifter” way?

大憨熊 提交于 2019-12-03 10:04:19

You can restrict external property manipulation, by marking the property public for reading and private for writing, as described in the documentation:

class RecordedAudio: NSObject {

    public private(set) let filePathUrl: NSURL!
    public private(set) let title: String?

    init(filePathUrl: NSURL, title: String?) {
        self.filePathUrl = filePathUrl
        self.title = title
    }

}

// in another file

let audio = RecordedAudio(filePathUrl: myUrl, title: myTitle)

let url = audio.filePathUrl // works, returns the url
audio.filePathUrl = newUrl // doesn't compile

I do it a bit like in Obj-C:

class MyClass
  private var _something:Int
  var something:Int {
    get {return _something}
// optional: set { _something = newValue }
  }
  init() { _something = 99 }
}

...
let c = MyClass()
let v = c.something

Above is a primitive example, but handled stringent it works as a good pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!