第一次接觸到init,看了官方的說明之後還是不太懂實際是做什麼的,但似乎有在接觸OO語言的都十分熟悉。
init就是初始化的概念,如果變數name在宣告type之後就結束了,並沒有賦值或是為空值,Swift認定name尚未初始化,所以compiler之後會出現錯誤:
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
init就是初始化的概念,如果變數name在宣告type之後就結束了,並沒有賦值或是為空值,Swift認定name尚未初始化,所以compiler之後會出現錯誤:
class NamedShape {
var numberOfSides: Int = 0
var name: String
//init(name: String) {
// self.name = name
//}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var numberOfSides: Int = 0
var name: String
//init(name: String) {
// self.name = name
//}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
Class 'NamedShape' has no initializers
要解決的話:
var name: String -> var name: String?
or
var name: String -> var name: String = "myString"
or
在後面加上
init(name: String) {
self.name = name
}
這樣就初始化完成了。
參考資料:
https://hugolu.gitbooks.io/learn-swift/content/Advanced/Class.html
https://gradyzhuo.gitbooks.io/meetswifttutorial/content/Episode_1/Chapter_1.html
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1