Calling instance method during initialization in Swift

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

    I think the Swift way to do this is with Computed Properties (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html)

    EDIT

    Instead of calling a function to modify a property on set/get, you can use computed properties:

    class MyClass {
    
        var x: String?
        var y: String? {
            get {
                return "\(x!)_test"
            }
        }
    
        init(x: String!){
           self.x = x
        }
    }
    
    let myClass = MyClass(x: "string") 
    print(myClass.y!) #=> "string_test"
    

提交回复
热议问题