Information Hiding the “Swifter” way?

前端 未结 2 1522
失恋的感觉
失恋的感觉 2021-02-11 04:19

I have a question regarding object oriented design principles and Swift. I am pretty familiar with Java and I am currently taking a udacity course to get a first hands on in Swi

相关标签:
2条回答
  • 2021-02-11 04:54

    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.

    0 讨论(0)
  • 2021-02-11 04:56

    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
    
    0 讨论(0)
提交回复
热议问题