Calling instance method during initialization in Swift

前端 未结 7 1522
别跟我提以往
别跟我提以往 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:49

    Convert createY() to a global or class function that accepts x as an argument and returns a y.

    func createY(x: String) -> String {
        return x + "_test" // this computation could be much more complex
    }
    

    Then just call it normally from your init.

    class MyClass {
      let x: String
      let y: String
    
      init(x: String) {
        self.x = x
        self.y = createY(x)
      }     
    }
    

提交回复
热议问题