Swift 2中的指定初始化器和便捷初始化器

时间:2016-06-08 17:48:28

标签: swift swift2 initialization

有人可以简单明了地解释一下指定初始值设定项和初始化程序之间的区别吗?如果可能的话用一些基本的例子来理解。感谢

2 个答案:

答案 0 :(得分:1)

便捷初始化器是调用指定初始值设定项的初始值设定项。在将大多数初始化委托给指定的初始化程序之前,它们通常用于处理某些默认参数或一些额外的功能。

这张图片给出了很好的解释:

initializers

答案 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

希望这个例子有助于澄清一些事情!