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

后端 未结 2 1719
误落风尘
误落风尘 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 05:57

    I don't think you're doing anything wrong.

    The language specification only says that a default parameter should come before non-default parameters (p169), and that the default value is defined by an expression (p637).

    It does not say what that expression is allowed to reference. It seems like it is not allowed to reference the instance on which you are calling the method, i.e., self, which seems like it would be necessary to reference self.niceAnimal.

    As a workaround, you could define the default parameter as an optional with a default value of nil, and then set the actual value with an "if let" that references the member variable in the default case, like so:

     class animal {
         var niceAnimal: Bool
         var numberOfLegs: Int
    
         init(numberOfLegs: Int, animalIsNice: Bool) {
             self.numberOfLegs = numberOfLegs
             self.niceAnimal = animalIsNice
         }
    
         func description(numberOfLegs: Int, animalIsNice: Bool? = nil) {
           if let animalIsNice = animalIsNice ?? self.niceAnimal {
             // print
           }
         }
     }
    
    0 讨论(0)
  • 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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题