前言
你自定義了一個數據類型后,是否希望像var num: Int = 10
這樣通過一個字面量初始化一個類型的實例呢?是的話,請看下文詳細介紹。
一、字面量類型(Literal Type)
在介紹字面量類型前,我們先認識下字面量的概念。
所謂字面量,是指一段能表示特定類型的值(如數值、布爾值、字符串)的源碼表達式(it is the source code representation of a fixed value)。比如下面例子:
let num: Int = 10
let flag: Bool = true
let str: String = "hello"
例子中的10
、true
、hello
都是字面量。
那什么是字面量類型呢?
字面量類型就是支持通過字面量進行實例初始化的數據類型,如例子中的Int
、Bool
、String
類型。
在Swift中,其的字面量類型有:
- 所有的數值類型: Int、Double、Float以及其的相關類型(如UInt、Int16、Int32等)
- 布爾值類型:Bool
- 字符串類型:String
- 組合類型:Array、Dictionary、Set
- 空類型:Nil
二、字面量協議(Literal Protocol)
Swift是如何讓上述的數據類型具有字面量初始化的能力呢?
答案是:實現指定的字面量協議。
所以,如果我們希望自定義的數據類型也能通過字面量進行初始化,只要實現對應的字面量協議即可。
Swift中的字面量協議主要有以下幾個:
-
ExpressibleByNilLiteral
// nil字面量協議 -
ExpressibleByIntegerLiteral
// 整數字面量協議 -
ExpressibleByFloatLiteral
// 浮點數字面量協議 -
ExpressibleByBooleanLiteral
// 布爾值字面量協議 -
ExpressibleByStringLiteral
// 字符串字面量協議 -
ExpressibleByArrayLiteral
// 數組字面量協議 -
ExpressibleByDictionaryLiteral
// 字典字面量協議
其中, ExpressibleByStringLiteral
字符串字面量協議相對復雜一點,該協議還依賴于以下2個協議(也就是說,實現ExpressibleByStringLiteral
時,還需要實現下面2個協議):
ExpressibleByUnicodeScalarLiteral
ExpressibleByExtendedGraphemeClusterLiteral
在 Swift3.0 之前,上述的字面量協議的名稱對應如下:
NilLiteralConvertible
IntegerLiteralConvertible
FloatLiteralConvertible
BooleanLiteralConvertible
StringLiteralConvertible
ArrayLiteralConvertible
DictionaryLiteralConvertible
三、字面量協議例子(Literal Protocol Example)
下面將會通過具體例子為大家演示如何通過實現上述的字面量協議。
下面的例子均已經上傳GitHub,查看下載請點擊LiteralProtocolExample
1、定義Moeny
類型,實現通過整數字面量、浮點數字面量、字符串字面量、布爾值字面量初始化Money
實例:
//: Playground - noun: a place where people can play
import UIKit
import Foundation
struct Money {
var value: Double
init(value: Double) {
self.value = value
}
}
// 實現CustomStringConvertible協議,提供description方法
extension Money: CustomStringConvertible {
public var description: String {
return "\(value)"
}
}
// 實現ExpressibleByIntegerLiteral字面量協議
extension Money: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
public init(integerLiteral value: IntegerLiteralType) {
self.init(value: Double(value))
}
}
// 實現ExpressibleByFloatLiteral字面量協議
extension Money: ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value: value)
}
}
// 實現ExpressibleByStringLiteral字面量協議
extension Money: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
if let doubleValue = Double(value) {
self.init(value: doubleValue)
} else {
self.init(value: 0)
}
}
// 實現ExpressibleByExtendedGraphemeClusterLiteral字面量協議
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
if let doubleValue = Double(value) {
self.init(value: doubleValue)
} else {
self.init(value: 0)
}
}
// 實現ExpressibleByUnicodeScalarLiteral字面量協議
public init(unicodeScalarLiteral value: StringLiteralType) {
if let doubleValue = Double(value) {
self.init(value: doubleValue)
} else {
self.init(value: 0)
}
}
}
// 實現ExpressibleByBooleanLiteral字面量協議
extension Money: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
let doubleValue: Double = value ? 1.0 : 0.0
self.init(value: doubleValue)
}
}
// 通過整數字面量初始化
let intMoney: Money = 10
// 通過浮點數字面量初始化
let floatMoney: Money = 10.1
// 通過字符串字面量初始化
let strMoney: Money = "10.2"
// 通過布爾值初始化
let boolMoney: Money = true
2、定義Book
類型,實現通過字典字面量、數組字面量、nil字面量初始化Book
實例:
//: Playground - noun: a place where people can play
import Foundation
struct Book {
public var id: Int
public var name: String
init(id: Int, name: String = "unnamed") {
self.id = id
self.name = name
}
}
// 實現CustomStringConvertible協議,提供description方法
extension Book: CustomStringConvertible {
public var description: String {
return "id:\(id)\nname:《\(name)》"
}
}
// 實現ExpressibleByDictionaryLiteral字面量協議
extension Book: ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Any
public init(dictionaryLiteral elements: (Key, Value)...) {
var dictionary = [Key: Value](minimumCapacity: elements.count)
for (k, v) in elements {
dictionary[k] = v
}
let id = (dictionary["id"] as? Int) ?? 0
let name = (dictionary["name"] as? String) ?? "unnamed"
self.init(id: id, name: name)
}
}
// 實現ExpressibleByArrayLiteral字面量協議
extension Book: ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = Any
public init(arrayLiteral elements: ArrayLiteralElement...) {
var id: Int = 0
if let eId = elements.first as? Int {
id = eId
}
var name = "unnamed"
if let eName = elements[1] as? String {
name = eName
}
self.init(id: id, name: name)
}
}
// 實現ExpressibleByNilLiteral字面量協議
extension Book: ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self.init()
}
}
// 通過字典字面量初始化
let dictBook: Book = ["id": 100, "name": "Love is Magic"]
print("\(dictBook)\n")
// 通過數組字面量初始化
let arrayBook: Book = [101, "World is word"]
print("\(arrayBook)\n")
// 通過nil字面量初始化
let nilBook: Book = nil
print("\(nilBook)\n")
四、關于 'not expressible by any literal
enum' Error
當你使用自定義數據類型定義枚舉時,可能會遇到以下類似錯誤:
raw type 'XX_TYPE' is not expressible by any literal
enum XX_ENUM: XX_TYPE
這是說你的自定義數據類型沒有實現字面量協議。然而需要注意的是,enum目前支持的字面量協議是有限制的,其目前只支持以下幾個字面量協議:
- ExpressibleByIntegerLiteral
- ExpressibleByFloatLiteral
- ExpressibleByStringLiteral
也就是說,若你的自定義數據類型實現的字面量協議沒有包含上面中的一個,就會得到此種錯誤。具體示例如下:
//: Playground - noun: a place where people can play
import Foundation
struct StockType {
var number: Int
}
// 實現CustomStringConvertible協議,提供description方法
extension StockType: CustomStringConvertible {
public var description: String {
return "Stock Number:\(number)"
}
}
// 實現Equatable協議,提供==方法
extension StockType: Equatable {
public static func ==(lhs: StockType, rhs: StockType) -> Bool {
return lhs.number == rhs.number
}
}
// 實現ExpressibleByDictionaryLiteral字面量協議
extension StockType: ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Any
public init(dictionaryLiteral elements: (Key, Value)...) {
var dictionary = [Key: Value](minimumCapacity: elements.count)
for (k, v) in elements {
dictionary[k] = v
}
let number = (dictionary["number"] as? Int) ?? 0
self.init(number: number)
}
}
// 實現ExpressibleByIntegerLiteral字面量協議
extension StockType: ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(number: value)
}
}
/*
若StockType沒有實現 ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral、ExpressibleByStringLiteral中的一個,會報錯誤:error: raw type 'StockType' is not expressible by any literal
*/
// 你可以嘗試去掉ExpressibleByIntegerLiteral的實現,看看編譯器報的錯誤
enum Stock: StockType {
case apple = 1001
case google = 1002
}
let appleStock = Stock.apple.rawValue
print("\(appleStock)")
上述例子中,定義了StockType
數據類型和Stock
枚舉類型。若StockType
去掉ExpressibleByIntegerLiteral
字面量的協議的實現,將會獲得上述的編譯錯誤。