Calling instance method during initialization in Swift

前端 未结 7 1542
别跟我提以往
别跟我提以往 2020-12-06 01:08

I am new to Swift and would like to initialize an object\'s member variable using an instance method like this:

class MyClass {
  var x: String
  var y: Stri         


        
7条回答
  •  臣服心动
    2020-12-06 01:51

    In Swift 3, I've been using this pattern,

    class MyClass {
      var x: String?
      private(set) lazy var y: String? = self.createY()
    
      init(x: String){ self.x = x }
    
      private func createY() -> String?
      {
        return "\(x ?? "nil") test"
      }
    }
    

    The secret sauce here is the use of private(set) lazy. This way, you can label your property a var. And lazy will delay initialization until after your init function has completed. Using private(set) only allows the functions inside this class to modify that property, including the lazy keyword, but not let public interfaces change it. Of course, if you want your interface to change your property, then you can also mark it internal (the default) or public. But you need to leave it marked a lazy var

提交回复
热议问题