swift - 使用属性作为同一类中方法的默认参数值

标签 swift

在 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/

相关文章:

ios - 将自定义颜色设置为 UITabBarItem 不起作用

ios - 为什么更新步进器值时我的 Collection View 消失?

swift - 整数值 ?? 0 == -1? "-": "+" What does this mean?

ios - UICollectionView 数据未正确显示

swift - 如何在初始化期间正确设置 subview 约束?

ios - 准备在 UITabbarController 中不调用 segue

ios - 什么是 objc_AssociationPolicy?它是如何工作的?

ios - 检测两个物体之间是否发生碰撞

ios - 在设置中禁用位置后无法重新启用位置

ios - 如何在 Swift 中将数据从一个 TableView 传递到另一个 TableView ?