Swift字面量(literal)

在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
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章