Files
knowledge-kit/Chapter1 - iOS/1.122.md
2024-04-27 13:01:58 +08:00

87 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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
```