Using a property as a default parameter value for a method in the same class

后端 未结 2 1721
误落风尘
误落风尘 2021-02-13 05:45

In a Swift class, I want to use a property as a default parameter value for a method of the same class.

Here is my code :

class animal {
    var niceAn         


        
2条回答
  •  一生所求
    2021-02-13 06:02

    I think for now you can only use literals and type properties as default arguments.

    The best option would be to overload the method, and you can implement the shorter version by calling the full one. I only used a struct here to omit the initializer.

    struct Animal {
    
        var niceAnimal: Bool
        var numberOfLegs: Int
    
        func description(#numberOfLegs: Int) {
            description(niceAnimal, numberOfLegs: numberOfLegs)
        }
    
        func description(animalIsNice: Bool, numberOfLegs: Int) {
            // do something
        }
    
    }
    

提交回复
热议问题