一、初始化的兩種方式javascript
1)這種方式有參數,在每次聲明新的實例的時候,你能夠在定義的同時給它的temperature賦一個不一樣的值。java
struct Fahrenheit {
var temperature: Double
init(temperature: Double) {
self.temperature = temperature
}
}
var f = Fahrenheit(temperature: 20)
print("The default temperature is \(f.temperature)° Fahrenheit")複製代碼
2)該方式每一個生成的實例的temperature都有一個默認值。git
struct Fahrenheit {
var temperature = 32.0
}複製代碼
二、帶有參數的構造器,調用的時候必須帶有參數列表。github
struct Color {
let red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red = white
green = white
blue = white
}
}
let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
//該句會報錯
let veryGreen = Color(0.0, 1.0, 0.0)複製代碼
三、你能夠用_
代替參數名swift
struct Celsius {
var temperatureInCelsius: Double
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let gelsius = Celsius(30)
print(gelsius.temperatureInCelsius)複製代碼
四、你能夠將在構造期間值不肯定的屬性聲明爲optional閉包
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// Prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese."複製代碼
五、構造器代理app
1)值類型(struct,enumeration)相對簡單,它們不支持繼承,只能調用本身的相關的構造器。函數
2)類的比較複雜,它們支持繼承。ui
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let basicRect = Rect()
let originRect = Rect(origin: Point(x: 2.0, y: 2.0),size: Size(width: 5.0, height: 5.0))
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),size: Size(width: 3.0, height: 3.0))複製代碼
六、Swift提供類的兩種構造器,指定構造器(designated initializers)和便利構造器(convenience initializers)
咱們首要的應該使用designated initializers,每一個類應至少有一個designated initializers,若是沒有必要的話,你能夠不寫convenience initializers。
1)聲明designated initializers的語法spa
init(`parameters`) {
`statements`
}複製代碼
2)聲明convenience initializers的語法
convenience init(`parameters`) {
`statements`
}複製代碼
例子:
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"複製代碼
七、可失敗的構造器(Failable Initializer)
可失敗的構造器的關鍵字爲init?
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
if let giraffe = someCreature {
print("An animal was initialized with a species of \(giraffe.species)")
}
// Prints "An animal was initialized with a species of Giraffe"
//當你傳遞一個空字符創的時候,它會直接返回nil
let anonymousCreature = Animal(species: "")
// anonymousCreature is of type Animal?, not Animal
if anonymousCreature == nil {
print("The anonymous creature could not be initialized")
}
// Prints "The anonymous creature could not be initialized"複製代碼
八、當你在init前面添加require關鍵字時,意味着該init方法必須在子類中實現。
class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}複製代碼
九、使用閉包或者函數設置默認的屬性值
struct Chessboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAt(row: Int, column: Int) -> Bool {
return boardColors[(row * 8) + column]
}
}
let board = Chessboard()
print(board.squareIsBlackAt(row: 0, column: 1))
// Prints "true"
print(board.squareIsBlackAt(row: 7, column: 7))
// Prints "false"複製代碼
Tips: