Swift的字面量類(lèi)型(Literal Type)和字面量協(xié)議(Literal Protocol)

前言

你自定義了一個(gè)數(shù)據(jù)類(lèi)型后,是否希望像var num: Int = 10這樣通過(guò)一個(gè)字面量初始化一個(gè)類(lèi)型的實(shí)例呢?是的話,請(qǐng)看下文詳細(xì)介紹。

一、字面量類(lèi)型(Literal Type)

在介紹字面量類(lèi)型前,我們先認(rèn)識(shí)下字面量的概念。

所謂字面量,是指一段能表示特定類(lèi)型的值(如數(shù)值、布爾值、字符串)的源碼表達(dá)式(it is the source code representation of a fixed value)。比如下面例子:

let num: Int = 10
let flag: Bool = true
let str: String = "hello"

例子中的10、truehello都是字面量。

那什么是字面量類(lèi)型呢?

字面量類(lèi)型就是支持通過(guò)字面量進(jìn)行實(shí)例初始化的數(shù)據(jù)類(lèi)型,如例子中的Int、Bool、String類(lèi)型。

在Swift中,其的字面量類(lèi)型有:

  • 所有的數(shù)值類(lèi)型: Int、Double、Float以及其的相關(guān)類(lèi)型(如UInt、Int16、Int32等)
  • 布爾值類(lèi)型:Bool
  • 字符串類(lèi)型:String
  • 組合類(lèi)型:Array、Dictionary、Set
  • 空類(lèi)型:Nil

二、字面量協(xié)議(Literal Protocol)

Swift是如何讓上述的數(shù)據(jù)類(lèi)型具有字面量初始化的能力呢?

答案是:實(shí)現(xiàn)指定的字面量協(xié)議。

所以,如果我們希望自定義的數(shù)據(jù)類(lèi)型也能通過(guò)字面量進(jìn)行初始化,只要實(shí)現(xiàn)對(duì)應(yīng)的字面量協(xié)議即可。

Swift中的字面量協(xié)議主要有以下幾個(gè):

  • ExpressibleByNilLiteral // nil字面量協(xié)議
  • ExpressibleByIntegerLiteral // 整數(shù)字面量協(xié)議
  • ExpressibleByFloatLiteral // 浮點(diǎn)數(shù)字面量協(xié)議
  • ExpressibleByBooleanLiteral // 布爾值字面量協(xié)議
  • ExpressibleByStringLiteral // 字符串字面量協(xié)議
  • ExpressibleByArrayLiteral // 數(shù)組字面量協(xié)議
  • ExpressibleByDictionaryLiteral // 字典字面量協(xié)議

其中, ExpressibleByStringLiteral 字符串字面量協(xié)議相對(duì)復(fù)雜一點(diǎn),該協(xié)議還依賴(lài)于以下2個(gè)協(xié)議(也就是說(shuō),實(shí)現(xiàn)ExpressibleByStringLiteral時(shí),還需要實(shí)現(xiàn)下面2個(gè)協(xié)議):

  • ExpressibleByUnicodeScalarLiteral
  • ExpressibleByExtendedGraphemeClusterLiteral

在 Swift3.0 之前,上述的字面量協(xié)議的名稱(chēng)對(duì)應(yīng)如下:

  • NilLiteralConvertible
  • IntegerLiteralConvertible
  • FloatLiteralConvertible
  • BooleanLiteralConvertible
  • StringLiteralConvertible
  • ArrayLiteralConvertible
  • DictionaryLiteralConvertible

三、字面量協(xié)議例子(Literal Protocol Example)

下面將會(huì)通過(guò)具體例子為大家演示如何通過(guò)實(shí)現(xiàn)上述的字面量協(xié)議。

下面的例子均已經(jīng)上傳GitHub,查看下載請(qǐng)點(diǎn)擊LiteralProtocolExample

1、定義Moeny類(lèi)型,實(shí)現(xiàn)通過(guò)整數(shù)字面量、浮點(diǎn)數(shù)字面量、字符串字面量、布爾值字面量初始化Money實(shí)例:
//: Playground - noun: a place where people can play

import UIKit
import Foundation

struct Money {
    var value: Double

    init(value: Double) {
        self.value = value
    }
}

// 實(shí)現(xiàn)CustomStringConvertible協(xié)議,提供description方法
extension Money: CustomStringConvertible {
    public var description: String {
        return "\(value)"
    }
}

// 實(shí)現(xiàn)ExpressibleByIntegerLiteral字面量協(xié)議
extension Money: ExpressibleByIntegerLiteral {
    typealias IntegerLiteralType = Int

    public init(integerLiteral value: IntegerLiteralType) {
        self.init(value: Double(value))
    }
}

// 實(shí)現(xiàn)ExpressibleByFloatLiteral字面量協(xié)議
extension Money: ExpressibleByFloatLiteral {
    public init(floatLiteral value: FloatLiteralType) {
        self.init(value: value)
    }
}

// 實(shí)現(xiàn)ExpressibleByStringLiteral字面量協(xié)議
extension Money: ExpressibleByStringLiteral {

    public init(stringLiteral value: StringLiteralType) {
        if let doubleValue = Double(value) {
            self.init(value: doubleValue)
        } else {
            self.init(value: 0)
        }
    }

    // 實(shí)現(xiàn)ExpressibleByExtendedGraphemeClusterLiteral字面量協(xié)議
    public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
        if let doubleValue = Double(value) {
            self.init(value: doubleValue)
        } else {
            self.init(value: 0)
        }
    }

    // 實(shí)現(xiàn)ExpressibleByUnicodeScalarLiteral字面量協(xié)議
    public init(unicodeScalarLiteral value: StringLiteralType) {
        if let doubleValue = Double(value) {
            self.init(value: doubleValue)
        } else {
            self.init(value: 0)
        }
    }
}

// 實(shí)現(xiàn)ExpressibleByBooleanLiteral字面量協(xié)議
extension Money: ExpressibleByBooleanLiteral {
    public init(booleanLiteral value: BooleanLiteralType) {
        let doubleValue: Double = value ? 1.0 : 0.0
        self.init(value: doubleValue)
    }
}

// 通過(guò)整數(shù)字面量初始化
let intMoney: Money = 10

// 通過(guò)浮點(diǎn)數(shù)字面量初始化
let floatMoney: Money = 10.1

// 通過(guò)字符串字面量初始化
let strMoney: Money = "10.2"

// 通過(guò)布爾值初始化
let boolMoney: Money = true

2、定義Book類(lèi)型,實(shí)現(xiàn)通過(guò)字典字面量、數(shù)組字面量、nil字面量初始化Book實(shí)例:
//: 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
    }
}

// 實(shí)現(xiàn)CustomStringConvertible協(xié)議,提供description方法
extension Book: CustomStringConvertible {
    public var description: String {
        return "id:\(id)\nname:《\(name)》"
    }
}

// 實(shí)現(xiàn)ExpressibleByDictionaryLiteral字面量協(xié)議
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)
    }
}

// 實(shí)現(xiàn)ExpressibleByArrayLiteral字面量協(xié)議
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)
    }
}

// 實(shí)現(xiàn)ExpressibleByNilLiteral字面量協(xié)議
extension Book: ExpressibleByNilLiteral {
    public init(nilLiteral: ()) {
        self.init()
    }
}

// 通過(guò)字典字面量初始化
let dictBook: Book = ["id": 100, "name": "Love is Magic"]
print("\(dictBook)\n")

// 通過(guò)數(shù)組字面量初始化
let arrayBook: Book = [101, "World is word"]
print("\(arrayBook)\n")

// 通過(guò)nil字面量初始化
let nilBook: Book = nil
print("\(nilBook)\n")

四、關(guān)于 'not expressible by any literal

enum' Error

當(dāng)你使用自定義數(shù)據(jù)類(lèi)型定義枚舉時(shí),可能會(huì)遇到以下類(lèi)似錯(cuò)誤:

raw type 'XX_TYPE' is not expressible by any literal
enum XX_ENUM: XX_TYPE

這是說(shuō)你的自定義數(shù)據(jù)類(lèi)型沒(méi)有實(shí)現(xiàn)字面量協(xié)議。然而需要注意的是,enum目前支持的字面量協(xié)議是有限制的,其目前只支持以下幾個(gè)字面量協(xié)議:

  • ExpressibleByIntegerLiteral
  • ExpressibleByFloatLiteral
  • ExpressibleByStringLiteral

也就是說(shuō),若你的自定義數(shù)據(jù)類(lèi)型實(shí)現(xiàn)的字面量協(xié)議沒(méi)有包含上面中的一個(gè),就會(huì)得到此種錯(cuò)誤。具體示例如下:

//: Playground - noun: a place where people can play

import Foundation

struct StockType {
    var number: Int
}

// 實(shí)現(xiàn)CustomStringConvertible協(xié)議,提供description方法
extension StockType: CustomStringConvertible {
    public var description: String {
        return "Stock Number:\(number)"
    }
}

// 實(shí)現(xiàn)Equatable協(xié)議,提供==方法
extension StockType: Equatable {
    public static func ==(lhs: StockType, rhs: StockType) -> Bool {
        return lhs.number == rhs.number
    }
}

// 實(shí)現(xiàn)ExpressibleByDictionaryLiteral字面量協(xié)議
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)
    }
}

// 實(shí)現(xiàn)ExpressibleByIntegerLiteral字面量協(xié)議
extension StockType: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: IntegerLiteralType) {
        self.init(number: value)
    }
}

/*
 若StockType沒(méi)有實(shí)現(xiàn) ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral、ExpressibleByStringLiteral中的一個(gè),會(huì)報(bào)錯(cuò)誤:error: raw type 'StockType' is not expressible by any literal
 */
// 你可以嘗試去掉ExpressibleByIntegerLiteral的實(shí)現(xiàn),看看編譯器報(bào)的錯(cuò)誤
enum Stock: StockType {
    case apple = 1001
    case google = 1002
}

let appleStock = Stock.apple.rawValue
print("\(appleStock)")

上述例子中,定義了StockType數(shù)據(jù)類(lèi)型和Stock枚舉類(lèi)型。若StockType去掉ExpressibleByIntegerLiteral字面量的協(xié)議的實(shí)現(xiàn),將會(huì)獲得上述的編譯錯(cuò)誤。

資料參考

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

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

  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young閱讀 4,169評(píng)論 1 10
  • 基礎(chǔ)部分(The Basics) 當(dāng)推斷浮點(diǎn)數(shù)的類(lèi)型時(shí),Swift 總是會(huì)選擇Double而不是Float。 結(jié)合...
    gamper閱讀 1,487評(píng)論 0 7
  • 烏金: 你好。從小到大,我都生活在害怕和無(wú)助當(dāng)中。好在有個(gè)大我6歲的姐姐,陪伴我一起度過(guò)了充滿(mǎn)恐懼的童年生活。 我...
    彼得貓烏金閱讀 334評(píng)論 0 5
  • 文/anMoo韓魔 我記得這是在簡(jiǎn)書(shū)上的一位母親臨摹女兒的畫(huà),當(dāng)時(shí)覺(jué)得好看就保存下來(lái)了,現(xiàn)在想起來(lái)畫(huà)這幅畫(huà)的時(shí)候卻...
    anMoo韓魔閱讀 420評(píng)論 0 2
  • 17歲那年,我的處女作發(fā)表了,題目叫《打賭》。內(nèi)容說(shuō)的是一位穿著樸素的農(nóng)村婦女到街上成衣攤買(mǎi)衣服,村婦看中一件顏色...
    和風(fēng)輕和閱讀 359評(píng)論 4 5

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