在 Swift 类中,我想使用一个属性作为同一个类的方法的默认参数值。
这是我的代码:
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
}
}
问题是我不能将我的 niceAnimal 属性用作默认函数值,因为它会触发编译时错误:
'animal.Type' does not have a member named 'niceAnimal'
我做错了什么吗?或者在 Swift 中是不可能的?如果那是不可能的,你知道为什么吗?
最佳答案
我不认为你做错了什么。
语言规范只说默认参数应该在非默认参数之前(p169),默认值由表达式定义(p637)。
它没有说明该表达式允许引用什么。似乎不允许引用您调用方法的实例,即 self,这似乎有必要引用 self.niceAnimal。
作为解决方法,您可以将默认参数定义为默认值为 nil 的可选参数,然后使用在默认情况下引用成员变量的“if let”设置实际值,如下所示:
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
}
}
}
关于swift - 使用属性作为同一类中方法的默认参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086210/