Calling instance method during initialization in Swift

前端 未结 7 1546
别跟我提以往
别跟我提以往 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条回答
  •  旧时难觅i
    2020-12-06 01:50

    As answered here, create a class function. I've added the full code.

    class MyClass {
        var x: String
        var y: String
    
        class func createY(x: String) -> String {
             return x + "_test" // this computation could be much more complex
        }
    
        init(x: String) {
            self.x = x
            self.y = MyClass.createY(x)
        }     
    }
    

提交回复
热议问题