Swift 5.1读书笔记

Swift 的阅读笔记

Swift is a powerful and intuitive programming language for macOS, iOS, watchOS, tvOS and beyond. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.

Swift是一种功能强大且直观的编程语言,适用于macOS,iOS,watchOS,tvOS等。 编写Swift代码是交互式且有趣的,语法简洁而又富有表现力,并且Swift包含开发人员喜欢的现代功能。 Swift代码在设计上是安全的,但也可以生成运行闪电般快的软件。

词汇 音标 中文
intuitive [ɪnˈtuːɪtɪv] adj. 直觉的;凭直觉获知的
interactive [ˌɪntərˈæktɪv] adj. 交互式的;相互作用的
concise [kənˈsaɪs] adj. 简明的,简洁的
lightning [ˈlaɪtnɪŋ] adj. 闪电般快的,飞快的;突然的

Introducing Swift 5.1

Swift 5.1 now makes it easier to create and share binary frameworks with others. It also includes features that make it easier to design better APIs and reduce the amount of common boilerplate code.

词汇 音标 中文
boilerplate [ˈbɔɪlərpleɪt] n. 样板文件;引用

Key Features

  • Module stability defines a new text-based module interface file that describes the API of a binary framework.
  • Property wrappers introduce a general purpose syntax for defining custom access patterns for property values.
  • Opaque result types help hide implementation details in APIs.
  • 'Self' can now be used for classes and value types.
  • Support for handling and updating diffs on collections of appropriate types.
  • Improvements to SIMD and String types.

词汇 音标 中文
stability [stəˈbɪləti] n. 稳定性;坚定,恒心
appropriate [əˈproʊpriət] adj. 适当的;恰当的;合适的

Modern

Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain. Even better, you don’t even need to type semi-colons. Inferred types make code cleaner and less prone to mistakes, while modules eliminate headers and provide namespaces. To best support international languages and emoji, Strings are Unicode-correct and use a UTF-8 based encoding to optimize performance for a wide-variety of use cases. Memory is managed automatically using tight, deterministic reference counting, keeping memory usage to a minimum without the overhead of garbage collection.

Swift是对编程语言的最新研究的结果,结合了数十年的Apple平台构建经验。 命名参数以简洁的语法表示,这使Swift中的API更加易于阅读和维护。 更好的是,您甚至不需要键入分号。 推断的类型使代码更整洁且不易出错,而模块则消除了标头并提供了名称空间。 为了最好地支持国际语言和表情符号,字符串是Unicode正确的,并使用基于UTF-8的编码来优化各种用例的性能。 使用严格的确定性引用计数自动管理内存,从而将内存使用量降至最低,而不会产生垃圾回收的开销。

词汇 音标 中文
combined [kəmˈbaɪnd] adj. 结合的;[数] 组合的
decades [ˈdekeɪd,dɪˈkeɪd] n. 数十年(decade的复数)
semi-colons [ˈsemikoʊlən] n. 分号
Inferred [ɪnˈfɜːr] adj. 推论的;推测出的
prone [proʊn] adj. 俯卧的;有…倾向的,易于…的
eliminate [ɪˈlɪmɪneɪt] vt. 消除;排除
deterministic [dɪˌtɜːrmɪˈnɪstɪk] adj. 确定性的;命运注定论的

struct Player {
    var name: String
    var highScore: Int = 0
    var history: [Int] = []

    init(_ name: String) {
        self.name = name
    }
}

var player = Player("Tomas")
  • Declare new types with modern, straightforward syntax. Provide default values for instance properties and define custom initializers.
    使用现代,直接的语法声明新类型。 提供实例属性的默认值并定义自定义初始化函数。
extension Player {
    mutating func updateScore(_ newScore: Int) {
        history.append(newScore)
        if highScore < newScore {
            print("\(newScore)! A new high score for \(name)! 🎉")
            highScore = newScore
        }
    }
}

player.updateScore(50)
// Prints "50! A new high score for Tomas! 🎉"
// player.highScore == 50

  • Add functionality to existing types using extensions, and cut down on boilerplate with custom string interpolations.

使用扩展向现有类型添加功能,并使用自定义字符串插值缩减样板。

extension Player: Codable, Equatable {}

import Foundation
let encoder = JSONEncoder()
try encoder.encode(player)

print(player)
// Prints "Tomas, games played: 1, high score: 50”
  • Quickly extend your custom types to take advantage of powerful language features, such as automatic JSON encoding and decoding.

快速扩展您的自定义类型,以利用强大的语言功能,例如自动JSON编码和解码。

let players = getPlayers()

// Sort players, with best high scores first
let ranked = players.sorted(by: { player1, player2 in
    player1.highScore > player2.highScore
})

// Create an array with only the players’ names
let rankedNames = ranked.map { $0.name }
// ["Erin", "Rosana", "Tomas"]

Perform powerful custom transformations using streamlined closures.

使用简化的闭包执行强大的自定义转换。

词汇 音标 中文
interpolations [ɪnˌtɜːrpəˈleɪʃn] n. 插入;篡改;填写;插值
streamlined ['strim,laɪnd] adj. 流线型的;改进的;最新型的

These forward-thinking concepts result in a language that is fun and easy to use.

Swift has many other features to make your code more expressive:

  • Generics that are powerful and simple to use
  • Protocol extensions that make writing generic code even easier
  • First class functions and a lightweight closure syntax
  • Fast and concise iteration over a range or collection
  • Tuples and multiple return values
  • Structs that support methods, extensions, and protocols
  • Enums can have payloads and support pattern matching
  • Functional programming patterns, e.g., map and filter
  • Native error handling using try / catch / throw
  • 强大且易于使用的泛型
  • 协议扩展使编写泛型代码更加容易
  • 一流的功能和轻量级的闭包语法
  • 在范围或集合上进行快速简洁的迭代
  • 元组和多个返回值
  • 支持方法,扩展和协议的Structs
  • Enums可以具有payloads并支持模式匹配
  • 函数式编程模式,例如map和filter
  • 使用try / catch / throw处理错误

Designed for Safety

Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, memory is automatically managed, and enforcement of exclusive access to memory guards against many programming mistakes. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries. This means that when you make a copy of something with that type, you know it won’t be modified elsewhere.

Another safety feature is that by default Swift objects can never be nil. In fact, the Swift compiler will stop you from trying to make or use a nil object with a compile-time error. This makes writing code much cleaner and safer, and prevents a huge category of runtime crashes in your apps. However, there are cases where nil is valid and appropriate. For these situations Swift has an innovative feature known as optionals. An optional may contain nil, but Swift syntax forces you to safely deal with it using the ? syntax to indicate to the compiler you understand the behavior and will handle it safely.

Swift消除了整个类的不安全代码。 变量总是在使用前进行初始化,检查数组和整数是否溢出,自动管理内存,并强制执行对内存的独占访问,以防止发生许多编程错误。 语法经过调整,可轻松定义您的意图-例如,简单的三个字符的关键字定义了变量( var )或常量( let )。 Swift大量利用值类型,尤其是对于诸如数组和字典之类的常用类型。 这意味着当您复制具有该类型的内容时,您将知道它不会在其他地方被修改。

另一个安全功能是,默认情况下Swift对象永远不能为nil 。 实际上,Swift编译器将阻止您尝试制作或使用带有编译时错误的nil对象。 这使编写代码更加干净和安全,并防止了应用程序中大量的运行时崩溃。 但是,在某些情况下, nil有效且适当。 对于这些情况,Swift具有一项称为可选功能的创新功能。 可选内容可能包含nil ,但是Swift语法会强制您使用?安全地对其进行处理。 语法,向编译器指示您了解该行为并将安全地对其进行处理。

  • Use optionals when you might have an instance to return from a function, or you might not.

  • Features such as optional binding, optional chaining, and nil coalescing let you work safely and efficiently with optional values.


词汇 音标 中文
entire [ɪnˈtaɪər] adj. 全部的,整个的;全体的
enforcement [ɪnˈfɔːrsmənt] n. 执行,实施;强制
exclusive [ɪkˈskluːsɪv] adj. 独有的;排外的;专一的
intent [ɪnˈtent] n. 意图;目的;含义
leverage [ˈlevərɪdʒ] n. 手段,影响力;杠杆作用;杠杆效率 v. 利用;举债经营
appropriate /əˈproʊpriət/ adj. 适当的;恰当的;合适的
innovative [ˈɪnəveɪtɪv] adj. 革新的,创新的;有创新精神的
coalescing [ˌkoʊəˈles] vi. 合并;结合;联合. vt. 使…联合;使…合并

Fast and Powerful

From its earliest conception, Swift was built to be fast. Using the incredibly high-performance LLVM compiler technology, Swift code is transformed into optimized native code that gets the most out of modern hardware. The syntax and standard library have also been tuned to make the most obvious way to write your code also perform the best whether it runs in the watch on your wrist or across a cluster of servers.

Swift is a successor to both the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.

词汇 音标 中文
wrist n. 手腕;腕关节
cluster [ˈklʌstər] n. 群;簇;丛;串
successor n. 继承者;后续的事物
primitives [ˈprɪmətɪv] adj. 原始的,远古的;n. 原始人

Great First Language

Swift can open doors to the world of coding. In fact, it was designed to be anyone’s first programming language, whether you’re still in school or exploring new career paths. For educators, Apple created free curriculum to teach Swift both in and out of the classroom. First-time coders can download Swift Playgrounds—an app for iPad that makes getting started with Swift code interactive and fun.

Aspiring app developers can access free courses to learn to build their first apps in Xcode. And Apple Stores around the world host Today at Apple Coding & Apps sessions where you can get hands-on experience with Swift code.


Source and Binary Compatibility

With Swift 5, you don’t have to modify any of your Swift 4 code to use the new version of the compiler. Instead you can start using the new compiler and migrate at your own pace, taking advantage of new Swift 5 features, one module at a time. And Swift 5 now introduces binary compatibility for apps. That means you no longer need to include Swift libraries in apps that target current and future OS releases, because the Swift libraries will be included in every OS release going forward. Your apps will leverage the latest version of the library in the OS, and your code will continue to run without recompiling. This not only makes developing your app simpler, it also reduces the size of your app and its launch time.


Playgrounds and Read-Eval-Print-Loop (REPL)

Much like Swift Playgrounds for iPad, playgrounds in Xcode make writing Swift code incredibly simple and fun. Type a line of code and the result appears immediately. You can then Quick Look the result from the side of your code, or pin that result directly below. The result view can display graphics, lists of results, or graphs of a value over time. You can open the Timeline Assistant to watch a complex view evolve and animate, great for experimenting with new UI code, or to play an animated SpriteKit scene as you code it. When you’ve perfected your code in the playground, simply move that code into your project. Swift is also interactive when you use it in Terminal or within Xcode’s LLDB debugging console. Use Swift syntax to evaluate and interact with your running app, or write new code to see how it works in a script-like environment.

Package Manager

Swift Package Manager is a single cross-platform tool for building, running, testing and packaging your Swift libraries and executables. Swift packages are the best way to distribute libraries and source code to the Swift community. Configuration of packages is written in Swift itself, making it easy to configure targets, declare products and manage package dependencies. New to Swift 5, the swift run command now includes the ability to import libraries in a REPL without needing to build an executable. Swift Package Manager itself is actually built with Swift and included in the Swift open source project as a package.

Objective-C Interoperability

You can create an entirely new application with Swift today, or begin using Swift code to implement new features and functionality in your app. Swift code co-exists alongside your existing Objective-C files in the same project, with full access to your Objective-C API, making it easy to adopt.

词汇 音标 中文
compatibility n. [计] 兼容性
evaluate vt. 评价;估价;求…的值
distribute vt. 分配;散布;分开;把…分类
adopt vt. 采取;接受;收养;正式通过
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,324评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,356评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,328评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,147评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,160评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,115评论 1 296
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,025评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,867评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,307评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,528评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,688评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,409评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,001评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,657评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,811评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,685评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,573评论 2 353