Swift Expressible Literal

引子

从一个面试题说起。有如下代码:

struct Book {
let name: String
} let book: Book = "Charlotte's Web"

请问是否可以让它正常编译?

字面量

字面量指字面代表的常量值。这样解释起来有点像废话。但是通过例子就很容易理解了。

以下是 Swift 中的一些字面量:

种类 示例
字符串 "ich", Bingo!
浮点型数字 1001.3, 33.0
整型数字 1001, 33
布尔值 true, false
数组 ["Emily", "Ben", "Eric"]
字典 ["name": "Ben"]
nil

Expressible Literal 协议

Swift 中,String, Float, Double, IntBool 等类型,和上面的 Book 一样,都是 struct 。那么它们是怎么实现将字面量直接创建实例的呢?以下是 Bool 类型的一个拓展:

extension Bool : ExpressibleByBooleanLiteral {

    /// Creates an instance initialized to the specified Boolean literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use a Boolean literal. Instead, create a new `Bool` instance by
/// using one of the Boolean literals `true` or `false`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// In this example, both assignments to the `printedMessage` variable call
/// this Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
public init(booleanLiteral value: Bool) /// A type that represents a Boolean literal, such as `Bool`.
public typealias BooleanLiteralType = Bool
}

再看看 Float 的一个拓展:

extension Float : ExpressibleByIntegerLiteral {

    /// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
public init(integerLiteral value: Int64) /// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
public typealias IntegerLiteralType = Int64
}

除了 ExpressibleByBooleanLiteralExpressibleByBooleanLiteral 类似的协议还有 ExpressibleByStringLiteral, ExpressibleByNilLiteral, ExpressibleByArrayLiteral 等等。

所以,最开始的那个题目,就有答案了。

注意上面两个大代码块里面的注释,都有一句 Do not call this initializer directly

Swift Expressible literal的更多相关文章

  1. 浅谈Swift集合类型

    Swift 的集合表现形式由数组和字典组成.它可以完美的存储任何呢想存储的东西. 数组是一个同类型的序列化列表集合,它用来存储相同类型的不同值.字典也是一个数组,但它的存值方式类似于Map,通过一对一 ...

  2. 使用swift 中的注意,不断完善中

    1. 应该充分利用swfit的新特性 比如如果按照oc里的习惯,调用一个delegate中都optional函数应该这样写 if delegate != nil && delegate ...

  3. Apple Swift编程语言入门教程

    Apple Swift编程语言入门教程 作者: 日期: 布衣君子 2015.09.22 目录 1   简介 2   Swift入门 3   简单值 4   控制流 5   函数与闭包 6   对象与类 ...

  4. Swift声明参考

    一条声明可以在你的程序里引入新的名字和构造.举例来说,你可以使用声明来引入函数和方法,变量和常量,或者来定义 新的命名好的枚举,结构,类和协议类型.你也可以使用一条声明来延长一个已经存在的命名好的类型 ...

  5. Swift数据类型简介(二)

    整数 整数就是没有小数部分的数字,比如42和-23.整数可以是有符号(正.负.零)或者无符号(正.零). Swift 提供了8,16,32和64位的有符号和无符号整数类型.这些整数类型和 C 语言的命 ...

  6. swift中文文档翻译之--字符串和字符

    字符串和字符 A string is an ordered collection of characters, such as "hello, world" or "al ...

  7. swift中文文档- 类型转换

    未翻译完 待续(英语烂,求斧正) Type Casting 类型转换 Type casting is a way to check the type of an instance, and/or to ...

  8. swift:类型转换(is用作判断检测、as用作类型向下转换)

    类型转换是一种检查类实例的方式,并且哦或者也是让实例作为它的父类或者子类的一种方式.   类型转换在Swift中使用is 和 as操作符实现.这两个操作符提供了一种简单达意的方式去检查值的类型或者转换 ...

  9. Swift学习笔记五

    基础运算符 Swift的大部分运算符和C及OC相同,也分一元二元多元的,这里只记录一些Swift特有的性质或写法. 赋值运算符( = ) 在等号右边是一个有多个值的元组时,它的成员值可以分解并同时分别 ...

随机推荐

  1. Day05_vue入门

    学于黑马和传智播客联合做的教学项目 感谢 黑马官网 传智播客官网 微信搜索"艺术行者",关注并回复关键词"乐优商城"获取视频和教程资料! b站在线视频 学习目标 ...

  2. statsmodels 示例

    Statsmodels 示例 https://www.statsmodels.org/stable/examples/index.html

  3. PythonFile对象的属性

    PythonFile对象的属性: 一个文件被打开后,使用对象进行接收,接收的对象即为 File 对象 示例: ''' file.closed 返回true如果文件已被关闭,否则返回false file ...

  4. PHP curl_multi_remove_handle函数

    (PHP 5) curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源 说明 int curl_multi_remove_handle ( resource ...

  5. luogu P6088 [JSOI2015]字符串树 可持久化trie 线段树合并 树链剖分 trie树

    LINK:字符串树 先说比较简单的正解.由于我没有从最简单的考虑答案的角度思考 所以... 下次还需要把所有角度都考察到. 求x~y的答案 考虑 求x~根+y~根-2*lca~根的答案. 那么问题变成 ...

  6. 记502 dp专练

    趁着503的清早 我还算清醒把昨天老师讲的内容总结一下,昨天有点迷了 至使我A的几道题都迷迷糊糊的.(可能是我太菜了) 这道题显然是 数字三角形的变形 好没有经过认真思考然后直接暴力了 这是很不应该的 ...

  7. Pandas 数据处理 | Datetime 在 Pandas 中的一些用法!

    Datatime 是 Python 中一种时间数据类型,对于不同时间格式之间的转换是比较方便的,而在 Pandas 中也同样支持 DataTime 数据机制,可以借助它实现许多有用的功能,例如 1,函 ...

  8. 声明式事务xml Spring

    !--JDBC事务管理器--><bean id="tansactionManager" class="org.springframework.jdbc.dat ...

  9. Python实现进度条和时间预估的示例代码

    一.前言 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人,我给大家 ...

  10. MySQL--->存储引擎及图形化工具

    本章目标: 掌握MySQL存储引擎的特点 掌握Navicat图形化工具的使用 了解其他的一些图形化管理工具 1.存储引擎种类: 2. 表级锁和行级锁: 3.常见的引擎: InnoDB 存储引擎 MyI ...