美文网首页
Swift字面量(literal)

Swift字面量(literal)

作者: Sweet丶 | 来源:发表于2022-12-03 15:22 被阅读0次

    在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
        }
    }
    

    相关文章

      网友评论

          本文标题:Swift字面量(literal)

          本文链接:https://www.haomeiwen.com/subject/cqwpfdtx.html