每天了解一点不一样的 Swift 小知识

代码截图

image.png

小笔记

这段代码在说什么

图示里的代码让 URL 遵守了 ExpressibleByStringLiteral 协议,并重写了其对应的构造器,使我们能够通过字符串的字面量直接创建 URL 对象。

如果想在 Swift 3 之前实现同样的功能,我们需要实现 URL 的 init(extendedGraphemeClusterLiteral value: StaticString)init(unicodeScalarLiteral value: StaticString) 方法。

示例代码里的 require(hint:) 方法出自 John Sundell 编写的开源库 Require,这个仓库主要的功能是帮助开发者轻松地处理 Optional 值不为 nil 的情况或者由 Optional 造成的崩溃。

Literal Type 是什么

在一些国外的 Swift 文章中,经常会提到 Literal Type,这里我们姑且称它为字面量类型。

要说清楚字面量类型,先说明一下什么是 Literal(字面量),Wiki 里面的定义) 是这样的。

Literal (computer programming) - In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values such as integers, floating-point numbers, and strings, and usually for booleans and characters; some also have notations for elements of enumerated types and compound values such as arrays, records, and objects. An anonymous function is a literal for the function type.

简单来说,所谓的字面量,就是指一段能够表示特定类型,特定值的源代码表达式,Swift 里面的 10, true, “Hello” 都是字面量。

在得到了字面量的定义后,我们就很容易得出字面类型的定义了!字面量类型就是支持通过字面量进行实例初始化的数据类型,如 Swift 中的 Int,Bool,String 类型。

下面的列表中,展示了在 Swift 语言中,常见的字面量类型和其对应的实例:

字面量类型的名称 默认的数据类型 示例
Integer Int 123, 0b1010, 0o644, 0xFF,
Floating-Point Double 3.14, 6.02e23, 0xAp-2
String String “Hello”, “”” . . . “””
Extended Grapheme Cluster Character “A”, “é”, “🇺🇸”
Unicode Scalar Unicode.Scalar “A”, “´”, “\u{1F1FA}”
Boolean Bool true, false
Nil Optional nil
Array Array [1, 2, 3]
Dictionary Dictionary [“a”: 1, “b”: 2]

小提示:不能直接使用 nil 的字面量,因为 Swift 的类型推断无法确定 nil 到底是何种类型,这里我们需要这样使用 nil 字面量

> nil // ! cannot infer type
> let a = nil as String?// Optional<String>.none
> let b: String? = nil
>

除了标准库以为,在 Playground 里面还有几个特定的字面量。

字面量类型的名称 默认的数据类型 示例
Color NSColor/UIColor #colorLiteral(red: 1, green: 0, blue: 1, alpha: 1)
Image NSImage / UIImage #imageLiteral(resourceName: “icon”)
File URL #fileLiteral(resourceName: “articles.json”)

利用 Literal Protocol 实现 Literal Type

既然知道了字面量类型,那么怎么让自己创建的数据类型拥有字面量初始化的能力呢?很简单,我们只需要遵循对应的协议并完成自己的实现即可!所以问题又来了,有哪些协议是开放给开发者使用的呢?

  • ExpressibleByIntegerLiteral
  • ExpressibleByFloatLiteral
  • ExpressibleByStringLiteral
  • ExpressibleByExtendedGraphemeClusterLiteral
  • ExpressibleByUnicodeScalarLiteral
  • ExpressibleByBooleanLiteral
  • ExpressibleByNilLiteral
  • ExpressibleByArrayLiteral
  • ExpressibleByDictionaryLiteral

其中需要注意的是 ExpressibleByStringLiteral 继承了 ExpressibleByExtendedGraphemeClusterLiteralExpressibleByUnicodeScalarLiteral 两个协议。

下面的例子展示了如何让一个自定义类型支持数字字面量初始化和字符串字面量初始化。

struct Money {
var value: Double
init(value: Double) {
self.value = value
}
}
// 实现ExpressibleByIntegerLiteral字面量协议
extension Money: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
public init(integerLiteral value: IntegerLiteralType) {
self.init(value: Double(value))
}
}
// 实现ExpressibleByStringLiteral字面量协议
extension Money: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
if let doubleValue = Double(value) {
self.init(value: doubleValue)
} else {
self.init(value: 0)
}
}
}
let intMoney: Money = 10 // 通过整数字面量初始化
let strMoney: Money = "10.2" // 通过字符串字面量初始化

Literal 在 Swift 5 里的进化

在 Swift 5 的发布过程中,核心团队接纳了社区的 SE-0200 提议,这个提议为 Swift 添加了与原始字符串字面量(Raw String Literals)相关的功能,在这项提议中反斜杠(\)和井号(#)在某些场景下是被当作为标点符号而不是转义字符或字符串终止符。这使得许多用法变得更容易,特别是正则表达式。

关于这个知识点可以阅读 Paul Hudson 的文章 - What’s new in Swift 5.0

Swift 5.0 里还有一个与字面量相关的提议 - SE-0213: Literal initialization via coercion,简单来说它就是让字面量的创建更加合理,也更加有效率了。

Literal Protocol 带来的好处

通过今天的 Tips,我们应该可以发现字面量协议是一个非常有意思的东西,通过它,我们甚至可以通过一个字符串来初始化一个 UIViewController !(但我估计不会有人想这么做…..)

虽然,这种自由度确实带来了许多可能性,但我确实没有想到十分贴合的业务场景,不过知道这个小技巧还是没什么不好的吧。

关于 Literal Protocol,你有什么好的使用场景么?