Using a property as a default parameter value for a method in the same class
swift
Solution
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
}
}
}
Problem
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 niceAnimal:Bool var numberOfLegs:Int init(numberOfLegs:Int,animalIsNice:Bool) { self.numberOfLegs = numberOfLegs self.niceAnimal = animalIsNice } func description(animalIsNice:Bool = niceAnimal,numberOfLegs:Int) { // I'll write my code here } } ``` The problem is that I can't use my niceAnimal property as a default function value, because it triggers me a compile-time error : 'animal.Type' does not have a member named 'niceAnimal' Am I doing something wrong ? Or is it impossible in Swift ? If that's impossible, do you know why ?