Swift 為我們提供一種非常優(yōu)雅的類實(shí)例化語法, Block 代碼塊實(shí)例化。
使用 Block 代碼塊實(shí)例化,可以減少不必要的命名沖突,同時可以讓代碼看起來更舒服。
使用 Block 代碼塊實(shí)例化的另一個好處是內(nèi)存的管理會變得更簡單。
讓我們看一個例子吧! 假設(shè)我們有一個Child類。
class Child {
var name: String?
var age: Int?
}
一個正常的實(shí)例化寫法是這樣的。
let myChild = Child()
myChild.name = "Pony"
myChild.age = 8
但是,使用 Block 進(jìn)行實(shí)例化,可以這樣寫。
let myChild: Child = {
let item = Child()
item.name = "Pony"
item.age = 8
return item
}()
在一個類方法中使用 Block 進(jìn)行實(shí)例化,如果 Block 中有 self 的引用,不要忘記添加 [unowned self] 標(biāo)簽,否則可能會有循環(huán)引用問題。
import UIKit
class Child {
var name: String?
var age: Int?
}
class Main {
let name = "Pony"
let age = 8
func sayHello() {
let myChild: Child = { [unowned self] in
let item = Child()
item.name = self.name
item.age = self.age
return item
}()
}
}
let x = Main()
x.sayHello()