简体   繁体   中英

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:

'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.

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

A much simpler solution is to replace class with struct .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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