有人可以简单明了地解释一下指定初始值设定项和初始化程序之间的区别吗?如果可能的话用一些基本的例子来理解。感谢
答案 0 :(得分:1)
答案 1 :(得分:1)
便捷初始化器提供了一种实例化类或结构的替代方法。便捷初始化程序必须调用默认初始值设定项。下面是一个非常基本的示例,可以帮助您查看类的有用性和语法:
import Foundation
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) { //default initizlier
self.firstName = firstName
self.lastName = lastName
}
convenience init(fullName: String) { //convenience initalizer to let user create instance of Person with a single string
var fname: String
var lname: String
var nameParts = fullName.componentsSeparatedByString(" ")
if nameParts.count == 1 {
fname = ""
lname = nameParts[0]
} else {
fname = nameParts.first ?? ""
lname = nameParts.last ?? ""
}
self.init(firstName: fname, lastName: lname) //must call the default initializer
}
}
let person1 = Person(firstName: "Fred", lastName: "Flintstone")
let person2 = Person(fullName: "Wilma Flintstone")
//let person3 = Person() //invalid due to no init() defined
print("\(person1.firstName) \(person1.lastName)") //Fred Flintstone
print("\(person2.firstName) \(person2.lastName)") //Wilma Flintstone
希望这个例子有助于澄清一些事情!