class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}
만약 상속된 초기자로 요구사항을 만족시킬 수 있다면 필수 초기자의 명시적 구현을 제공하지 않아도 된다.
class SomeClass {
let someProperty: SomeType = {
// create a default value for someProperty inside this closure
// someValue must be of the same type as SomeType
return someValue
}()
}
프로퍼티 초기화에 클로저를 사용할 땐 클로저가 실행되는 순간에는 인스턴스의 나머지 프로퍼티들은 초기화되지 않은 상황임을 기억해야 한다. 이는 다른 프로퍼티들이 기본값을 가지고 있어도, 클로저 내에서는 다른 프로퍼티 값에 접근할 수 없다는 뜻이다. 또한 암시적 self 프로퍼티를 사용하거나 인스턴스 메소드를 호출할 수 없다.
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"