![](/img/trans.png)
[英]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.