简体   繁体   English

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

[英]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.

相关问题 Swift:Enum&#39;无法构造,因为它没有可访问的初始值设定项&#39; - Swift : Enum 'cannot be constructed because it has no accessible initializers' 错误:'结果<data, foursquareerror> ' 无法构造,因为它没有可访问的初始值设定项</data,> - Error: 'Result<Data, FourSquareError>' cannot be constructed because it has no accessible initializers 无法构造&#39;UITabBarDelegate&#39;,因为它没有可访问的初始化程序 - 'UITabBarDelegate' cannot be constructed because it has no accessible initializers 无法构造委托,因为它没有可访问的初始化程序? - Delegate cannot be constructed because it has no accessible initializers? 无法构造“ CLLocationManagerDelegate”,因为它没有可访问的初始化程序 - 'CLLocationManagerDelegate' cannot be constructed because it has no accessible initializers 无法构建&#39;DepartmentDataDelegate&#39;,因为它没有可访问的初始化程序 - 'DepartmentDataDelegate' cannot be constructed because it has no accessible initializers 枚举:“无法构造,因为它没有可访问的初始值设定项” - Enumeration: “cannot be constructed because it has no accessible initializers” 无法构造“任务”,因为它没有可访问的初始值设定项 - 'Task' cannot be constructed because it has no accessible initializers Swift:为什么使用MKPointAnnotation而不使用MKAnnotation。 无法构造“ MKAnnotation”错误,因为它没有可访问的初始化程序。 - Swift: why MKPointAnnotation and not MKAnnotation. Errors out with “'MKAnnotation' cannot be constructed because it has no accessible initializers” 为什么我在 Swift 中得到这个“无法构造,因为它没有可访问的初始值设定项” - Why do I get this in Swift “cannot be constructed because it has no accessible initializers”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM