mirror of
https://github.com/NohamR/knowledge-kit.git
synced 2026-05-24 20:00:37 +00:00
87 lines
3.0 KiB
Markdown
87 lines
3.0 KiB
Markdown
# 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
|
||
```
|
||
|
||
<img src="https://github.com/FantasticLBP/knowledge-kit/raw/master/assets/SwiftChangeLiteral.png" style="zoom:25%">
|
||
|
||
|
||
|
||
## 字面量协议
|
||
|
||
Swift 自带的数据类型基本都可通过字面量初始化,本质原因是遵循了对应的协议
|
||
|
||
| | | |
|
||
| ------------- | ------------------------------------------------------ | ------------------------------------------------------------ |
|
||
| Bool | ExpressibleByBooleanLiteral | var b:Bool = false |
|
||
| Int | ExpressibleByIntegerLiteral | var num:Int = 2 |
|
||
| Float、Double | ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral | var height:Float = 175 <br>var height1:Float = 175.2 <br>var weight:Double = 130 <br>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<Int> = 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
|
||
```
|
||
|