簡體   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