Swift-字面量

【返回目錄】



字面量(Literal)

  • 下面代碼中的10、false、"Jack"都是字面量
var age = 10
var isRed = false
var name = "Jack"


  • Swift源碼規(guī)定,常見字面量的默認類型:
public typealias IntegerLiteralType = Int
public typealias FloatLiteralType = Double
public typealias BooleanLiteralType = Bool
public typealias StringLiteralType = String


  • 可以通過typealias修改字面量的默認類型
typealias FloatLiteralType = Float
typealias IntegerLiteralType = UInt8
var age = 10 // UInt8
var height = 1.68 // Float
  • Swift自帶的絕大部分類型,都支持直接通過字面量進行初始化,如下:
Bool、Int、Float、Double、String、Array、Dictionary、Set、Optional等




字面量協(xié)議

  • Swift自帶類型之所以能夠通過字面量初始化,是因為它們遵守了對應的協(xié)議
    • Bool : ExpressibleByBooleanLiteral
    • Int : ExpressibleByIntegerLiteral
    • Float、Double : ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral
    • Dictionary : ExpressibleByDictionaryLiteral
    • String : ExpressibleByStringLiteral
    • Array、Set : ExpressibleByArrayLiteral
    • Optional : ExpressibleByNilLiteral
var b: Bool = false // ExpressibleByBooleanLiteral
var i: Int = 10 // ExpressibleByIntegerLiteral
var f0: Float = 10 // ExpressibleByIntegerLiteral
var f1: Float = 10.0 // ExpressibleByFloatLiteral
var d0: Double = 10 // ExpressibleByIntegerLiteral
var d1: Double = 10.0 // ExpressibleByFloatLiteral
var s: String = "jack" // ExpressibleByStringLiteral
var arr: Array = [1, 2, 3] // ExpressibleByArrayLiteral
var set: Set = [1, 2, 3] // ExpressibleByArrayLiteral
var dict: Dictionary = ["jack" : 60] // ExpressibleByDictionaryLiteral
var o: Optional<Int> = nil // ExpressibleByNilLiteral




字面量協(xié)議的應用

  • 讓Int類型遵守ExpressibleByBooleanLiteral協(xié)議,這樣就能通過Bool字面量來初始化Int類型數(shù)據(jù)
//有點類似于C++中的轉(zhuǎn)換構(gòu)造函數(shù)
extension Int : ExpressibleByBooleanLiteral {
    public init(booleanLiteral value: Bool) {
        self = value ? 1 : 0
    }
}
var num: Int = true //通過Bool字面量來初始化Int類型數(shù)據(jù)
print(num) // 1


  • 使用Int、Double、String類型字面量來初始化Student對象
class Student : ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, CustomStringConvertible {
    var name: String = ""
    var score: Double = 0
    required init(floatLiteral value: Double) { self.score = value }
    required init(integerLiteral value: Int) { self.score = Double(value) }
    required init(stringLiteral value: String) { self.name = value } //使用一般String
    required init(unicodeScalarLiteral value: String) { self.name = value } //unicode表情
    required init(extendedGraphemeClusterLiteral value: String) { self.name = value } //特殊字符
    var description: String { "name=\(name),score=\(score)" }
}
var stu: Student = 90
print(stu) // name=,score=90.0
stu = 98.5
print(stu) // name=,score=98.5
stu = "Jack"
print(stu) // name=Jack,score=0.0


  • 使?數(shù)組、字典字?量初始化Point
struct Point {
    var x = 0.0, y = 0.0
}
extension Point : ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { 
    init(arrayLiteral elements: Double...) { //使用數(shù)組初始化
    guard elements.count > 0 else { return }
    self.x = elements[0]
    guard elements.count > 1 else { return }
    self.y = elements[1]
}
    init(dictionaryLiteral elements: (String, Double)...) { //使用字典初始化
        for (k, v) in elements {
            if k == "x" { self.x = v }
            else if k == "y" { self.y = v }
        }
    }
}
var p: Point = [10.5, 20.5]
print(p) // Point(x: 10.5, y: 20.5)
p = ["x" : 11, "y" : 22]
print(p) // Point(x: 11.0, y: 22.0)




【轉(zhuǎn)自:https://juejin.cn/post/7226157821708386365】






【上一篇】:內(nèi)存管理
【下一篇】:模式匹配




最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容