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

后端 未结 2 1756
误落风尘
误落风尘 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条回答
  •  萌比男神i
    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
           }
         }
     }
    

提交回复
热议问题