在Swift中,可以通過字面量來初始化實例,比如:var a = 1
, 就是通過字面量1
初始化一個Int實例。那麼爲什麼能通過字面量初始化實例呢?接下來我們學習下字面量的知識。
一、字面量初始化實例
下面列舉了通過字面量來初始化的類型,後面的註釋是該類型遵守的字面量協議,一個類型可以通過字面量來初始化的原因是遵守了對應的協議。
func testLiteral() {
var b: Bool = false // ExpressibleByBooleanLiteral
var i: Int = 10 // ExpressibleByIntegerLiteral
var f0: Float = 10 // ExpressibleByIntegerLiteral
var f1: Float = 10.1 // ExpressibleByFloatLiteral
var d0: Double = 10 // ExpressibleByIntegerLiteral
var d1: Double = 10.1 // ExpressibleByFloatLiteral
var s: String = "dandy" // ExpressibleByStringLiteral
var arr: Array = [1, 2, 3] // ExpressibleByArrayLiteral
var set: Set = [1, 2, 3] // ExpressibleByArrayLiteral
var dict: Dictionary = ["dandy": 30] // ExpressibleByDictionaryLiteral
var o: Optional<Int> = nil // ExpressibleByNilLiteral
// 按字符串插值表示
let message = "One cookie: $\(f1), \(f0) cookies: $\(f0 * f1)." // ExpressibleByStringInterpolation
// 按Unicode標量文字表示
let ñ: Unicode.Scalar = "ñ" // ExpressibleByUnicodeScalarLiteral
let n: String = "ñ" //ExpressibleByUnicodeScalarLiteral
let n2: Character = "ñ" //ExpressibleByUnicodeScalarLiteral
// 擴展的字素簇
let snowflake: Character = "❄︎" // ExpressibleByExtendedGraphemeClusterLiteral
let snowflakeStr: String = "❄︎" // ExpressibleByExtendedGraphemeClusterLiteral
}
二、自定義通過字面量初始化實例的方式
如果希望自己的類型實例可以通過字面量初始化,只需要遵守相應字面量協議即可。
class ZLStudent: ExpressibleByStringLiteral, ExpressibleByIntegerLiteral {
var name: String = ""
var score: Double = 0
required init(integerLiteral value: IntegerLiteralType) {
self.score = Double(value)
}
required init(stringLiteral value: StringLiteralType) {
self.name = value
}
}