繁体   English   中英

Swift 错误:无法构造“Human”,因为它没有可访问的初始值设定项

[英]Swift Error: 'Human' cannot be constructed because it has no accessible initializers

我正在尝试从 swift 中的 class 实例化 object。实例化时出现此错误:

'Human'cannot be constructed because it has no accessible initializers

我的代码:

class Human{
    var firstName: String
    var lastName : String
    var age : Int
    var spouseName: String?
    var childName : String?
    var currentSpeed: Double = 0

    func walk(speedIncrease: Double){
        currentSpeed += speedIncrease*2
    }
    func brake(){
        self.currentSpeed = 0
    }
}  

let  tanvir = Human(firstName: "tanvir", lastName:"Alam", age: 32, currentSpeed:30)
print("gmk")

我究竟做错了什么? 请解释。 谢谢你。

与初始化器是合成类的结构不同,类需要显式的init方法。

添加

init(firstName : String, lastName: String, age: Int, currentSpeed: Double = 0.0 {
    self.firstName = firstName
    self.lastName = lastName
    self.age = age
    self.currentSpeed = currentSpeed
}

并删除currentSpeed的默认值

一个更简单的解决方案是用struct替换class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM