在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'没有名为'niceAnimal'的成员
我做错了吗?或者在Swift中是不可能的?如果那是不可能的,你知道为什么吗?
答案 0 :(得分:9)
我不认为你做错了什么。
语言规范仅表示默认参数应位于非默认参数之前(p169),默认值由表达式(p637)定义。
它没有说明允许引用该表达式的内容。似乎不允许引用你调用方法的实例,即self,这似乎有必要引用self.niceAnimal。
作为一种变通方法,您可以将默认参数定义为可选,默认值为nil,然后使用&#34设置实际值;如果让"在默认情况下引用成员变量,如下所示:
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
}
}
}
答案 1 :(得分:0)
我认为现在你只能使用文字和类型属性作为默认参数。
最好的选择是重载方法,你可以通过调用完整的方法来实现更短的版本。我在这里只使用了一个结构来省略初始化器。
struct Animal {
var niceAnimal: Bool
var numberOfLegs: Int
func description(#numberOfLegs: Int) {
description(niceAnimal, numberOfLegs: numberOfLegs)
}
func description(animalIsNice: Bool, numberOfLegs: Int) {
// do something
}
}