What’s New in Swift 3? 笔记

标签(空格分隔): 译文


关于 API 的

  • 很多 APIs 改名了,具体请看API Design Guidelines
  • 调用函数或者方法第一个参数有参数名了。
// old way, Swift 2, followed by new way, Swift 3

"RW".writeToFile("filename", atomically: true, encoding: NSUTF8StringEncoding)
"RW".write(toFile: "filename", atomically: true, encoding: NSUTF8StringEncoding)

SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10)
SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 10)

UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
UIFont.preferredFont(forTextStyle: UIFontTextStyleSubheadline)

override func numberOfSectionsInTableView(tableView: UITableView) -> Int
override func numberOfSections(in tableView: UITableView) -> Int

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
func viewForZooming(in scrollView: UIScrollView) -> UIView?

NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: #selector(reset), userInfo: nil, repeats: true)
NSTimer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(reset), userInfo: nil, repeats: true)

你可以看到以上代码有很多介词,这是为了优化可读性。

你现在可以看到很多重载的方法名,因为 APIs 变得更加直白,下面有2个 index():的例子:

let names = ["Anna", "Barbara"]
if let annaIndex = names.index(of: "Anna") {
  print("Barbara's position: \(names.index(after: annaIndex))")
}

总而言之,参数名的改变让方法名变得更加统一和容易学习。

  • 删减了不必要的单词,让 API 变得更加 Swifty[SE-0005]:
// old way, Swift 2, followed by new way, Swift 3
let blue = UIColor.blueColor()
let blue = UIColor.blue()

let min = numbers.minElement()
let min = numbers.min()

attributedString.appendAttributedString(anotherString)
attributedString.append(anotherString)

names.insert("Jane", atIndex: 0)
names.insert("Jane", at: 0)

UIDevice.currentDevice()
UIDevice.current()

GCD and Core Graphics

GCD 被用于很多线程任务类似于与服务器通讯和大量计算。libdispatch库使用 C 语言写的并且经常使用 C style API。现在 API 变得更加 Swifty[SE-0088]:


// old way, Swift 2
let queue = dispatch_queue_create("com.test.myqueue", nil)
dispatch_async(queue) {
    print("Hello World")
}

// new way, Swift 3
let queue = DispatchQueue(label: "com.test.myqueue")
queue.asynchronously {
  print("Hello World")
}

Core Graphics 和 GCD 一样,请看[SE-0044]:

// old way, Swift 2
let ctx = UIGraphicsGetCurrentContext()
let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
CGContextSetFillColorWithColor(ctx, UIColor.blueColor().CGColor)
CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor)
CGContextSetLineWidth(ctx, 10)
CGContextAddRect(ctx, rectangle)
CGContextDrawPath(ctx, .FillStroke)
UIGraphicsEndImageContext()

// new way, Swift 3
if let ctx = UIGraphicsGetCurrentContext() {
    let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
    ctx.setFillColor(UIColor.blue().cgColor)
    ctx.setStrokeColor(UIColor.white().cgColor)
    ctx.setLineWidth(10)
    ctx.addRect(rectangle)
    ctx.drawPath(using: .fillStroke)

    UIGraphicsEndImageContext()
}

Capitalization on Enumeration Cases

Swift3 枚举的成员首字母变成了小写

// old way, Swift 2, followed by new way, Swift 3
UIInterfaceOrientationMask.Landscape
UIInterfaceOrientationMask.landscape

NSTextAlignment.Right
NSTextAlignment.right

SKBlendMode.Multiply
SKBlendMode.multiply

具体请看[SE-0006]:

Methods that Return or Modify

方法后缀如果是“-ed” 或者 “-ing” ,那么这个方法是个动词,且有返回值。如果一个方法没有后缀,那么这个方法是个名词,不返回值,只进行一些操作。


customArray.enumerate()
customArray.enumerated()

customArray.reverse()
customArray.reversed()

customArray.sort() // changed from .sortInPlace()
customArray.sorted()

var ages = [21, 10, 2] // variable, not constant, so you can modify it
ages.sort() // modified in place, value now [2, 10, 21]

for (index, age) in ages.enumerated() { // "-ed" noun returns a copy
  print("\(index). \(age)") // 1. 2 \n 2. 10 \n 3. 21
}

Function Types

在之前的语法中,省略了圆括号让参数在哪里结束和返回值在哪里开始变得很难懂

func g(a: Int -> Int) -> Int -> Int  { ... } // old way, Swift 2

现在变成了这样:

func g(a: (Int) -> Int) -> (Int) -> Int  { ... } // new way, Swift 3

// old way, Swift 2
Int -> Float
String -> Int
T -> U
Int -> Float -> String

// new way, Swift 3
(Int) -> Float
(String) -> Int
(T) -> U
(Int) -> (Float) -> String

API Additions

增加了几个有用的 API

Accessing the Containing Type

当你使用类方法或者类属性时,之前都必须像这样做:

CustomStruct.staticMethod()

现在可以使用首字母大写的 Self来代替以前的写法,并且用类的实例也能调用类方法或者类属性了:

struct CustomStruct {
  static func staticMethod() { ... }

  func instanceMethod()
    Self.staticMethod() // in the body of the type
  }
}

let customStruct = CustomStruct()
customStruct.Self.staticMethod() // on an instance of the type

Inline Sequences

有2个新方法sequence(first:next:)sequence(first:next:)返回无穷大的顺序序列,除非 next 返回 nil。

for view in sequence(first: someView, next: { $0.superview }) {
    // someView, someView.superview, someView.superview.superview, ...
}

还可以使用prefix来约束条件

for x in sequence(first: 0.1, next: { $0 * 2 }).prefix(while: { $0 < 4 }) {
  // 0.1, 0.2, 0.4, 0.8, 1.6, 3.2
}

具体查看 [SE-0045]:

Miscellaneous Odds and Ends

  • #keyPath()#selector()类似,可以帮助你防止错误字在使用字符串类型 API 时
  • 使用pi可以获得圆周率,具体请看 [SE-0067]
  • NS 前缀被取消,Date替代NSDate

Improvements to Tooling

Swift3 提高了提示错误和警告信息的精准度,并且他的运行和编译速度也更快了:

  • 通过改进字符串 hashing 提高了3倍速度在字符串字典中
  • 通过将对象从堆移到栈中提高了24倍速度(在某些情况下)
  • 编译器可以一次缓存很多文件
  • 减小了编译后的大小

The Swift Package Manager

你也许会使用 Cocoapods 或者 Cocoapods,Swift 包管理将会下载依赖,编译他们然后链接在一起来创建库和可执行文件。

Planned Future Features

Swift3 不会马上包含 ABI。ABI 其实是一个二进制接口,比 API 更底层,ABI 的作用就是不管 Swift 怎么迭代,你还是可以一直使用老版本 Swift 编译的第三方库。

这篇文章同时发布在我的 Git 上,这个项目我会更新一些平时学习的资源和笔记,有兴趣的朋友可以 Watch 一下。

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

推荐阅读更多精彩内容