[英]Swift Error: 'Human' cannot be constructed because it has no accessible initializers
I am trying to instantiate an object from a class in swift. When I instantiate I am getting this error:我正在尝试从 swift 中的 class 实例化 object。实例化时出现此错误:
'Human'cannot be constructed because it has no accessible initializers
My Codes:我的代码:
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")
What am I doing wrong?我究竟做错了什么? Please Explain.
请解释。 Thank You.
谢谢你。
Unlike structs where the initializer is synthesized classes require an explicit init
method.与初始化器是合成类的结构不同,类需要显式的
init
方法。
Add添加
init(firstName : String, lastName: String, age: Int, currentSpeed: Double = 0.0 {
self.firstName = firstName
self.lastName = lastName
self.age = age
self.currentSpeed = currentSpeed
}
and remove the default value of currentSpeed
并删除
currentSpeed
的默认值
A much simpler solution is to replace class
with struct
.一个更简单的解决方案是用
struct
替换class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.