# Swift 字面量本质 ## 常见的字面量默认类型 - `public typealias IntegerLiteralType = Int` - `public typealias FloatLiteralType = Float` - `public typealias BooleanLiteralType = Bool` - `public typealias StringLiteralType = String` 可以通过 typealias 修改字面量的默认类型,Demo 如下: ```swift typealias IntegerLiteralType = UInt8 var val = 8 val ``` ## 字面量协议 Swift 自带的数据类型基本都可通过字面量初始化,本质原因是遵循了对应的协议 | | | | | ------------- | ------------------------------------------------------ | ------------------------------------------------------------ | | Bool | ExpressibleByBooleanLiteral | var b:Bool = false | | Int | ExpressibleByIntegerLiteral | var num:Int = 2 | | Float、Double | ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral | var height:Float = 175
var height1:Float = 175.2
var weight:Double = 130
var weight1:Double = 130.1 | | Dictionary | ExpressibleByDictionaryLiteral | var dic:Dictionary = ["name": "FantasticLBP"] | | String | ExpressibleByStringLiteral | var name:String = "FantasticLBP" | | Array、Set | ExpressibleByArrayLiteral | var arr:Array = [1, 2, 3] | | Optional | ExpressibleByNilLiteral | var o:Optional = nil | ## 字面量协议的使用 Demo1 ```swift extension Int : ExpressibleByBooleanLiteral { public init(booleanLiteral value: Bool) { self = value ? 1 : 0 } } var num: Int = true print(num) // 1 num = false print(num) // 0 ``` Demo2 ```swift class Student: ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, CustomStringConvertible { var name: String = "" var score: Double = 0 required init(floatLiteral value: FloatLiteralType) { self.score = value } required init(stringLiteral value: StringLiteralType) { self.name = value } required init(integerLiteral value: IntegerLiteralType) { self.score = Double(value) } required init(extendedGraphemeClusterLiteral value: String) { self.name = value } required init(unicodeScalarLiteral value: String) { self.name = value } var description: String { "name is \(self.name), score is \(self.score)" } } var student: Student = "杭城小刘" print(student) // name is 杭城小刘, score is 0.0 student = 100 print(student) // name is , score is 100.0 ```