[英]Swift : Enum 'cannot be constructed because it has no accessible initializers'
[英]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.