Learning Swift 3.0 - 从精通到重新入门

来源:互联网 发布:鹰击长空2网络连接失败 编辑:程序博客网 时间:2024/05/20 14:16

    • 前言
    • API命名简化
    • C式API替换
      • GCD api
      • Core Graphics api
    • 大写开头的enum变成小写
    • 取消NS前缀
    • 参数label表现一致
    • 隐式解包可选ImplicitlyUnwrappedOptional
    • 类方法
    • 去掉了C风格的For循环
    • 去掉了柯里化语法
    • 去掉了 --语法
    • Swift Package Manager

前言

Swift 3.0是 Swift 加入到开源社区以来,第一次发布大版本。

作为下一代的Apple官方语言,从 Swift 2 开始,已经算是一门比较完善的语言了,完全可以当做iOS和macOS开发的主力,Swift 1 > 2 > 3 的改变,可以看出Apple的思路:

  • Swift 1 作为一个新的语言,紧抱Objective-C大腿,除了现代的语法,api几乎照搬,以便原来的开发者能够继续以Objective-C思维模式使用Swift开发,尽量吸引新老开发者,至于语言的稳定性,做的并不好。

  • Swift 2 则巩固1代的成果,提出的新语法寥寥无几(改进了的异常处理,something else…),Apple着力于加强它的稳定性和兼容性,加强了对这个语言的推广,最终在 2.2 版本加入了开源社区,现在已经被移植到了linux平台,甚至曾经被移植到Android上。

  • 在新的 Swift 3 里,语法上的变化已经开始减少了,多的是API的调整,Apple现在做的事,像是在减少Objective-C和C对Swift的影响,新式的API变得简单了,特别是C,Core打头的各种API,大多都被完全用Swift重写了:

let path = CGMutablePath()path.move(transform: &transform, x: topLeft.x, y: topLeft.y)

总的感觉就是:出道这么久,Swift要自立门户了。
广大开发者们常说:Swift 3.0 - 从精通到重新入门,这一天终于来了。
现在来看看Swift 3 有什么新变化吧,以下只是自己总结,不太全,未完待续↓

API命名简化

  • 优化将方法名切分,将操作中的动词提取,作为方法名.将其余部分作为参数名.

  • 在不引起歧义的情况下,去掉了重复性的名词.

// old code (Swift 2.2)let content = text.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())// new code (Swift 3.0)let content2 = text.trimmingCharacters(in: .newlines)

C式API替换

很多Core打头和常用的C的api,在新的swift中全部重写成了swift风格的,如下:

GCD api

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

Core Graphics api

// old way, Swift 2let 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 3if 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()}

大写开头的enum变成小写

// old way, Swift 2, followed by new way, Swift 3UIInterfaceOrientationMask.LandscapeUIInterfaceOrientationMask.landscapeNSTextAlignment.RightNSTextAlignment.rightSKBlendMode.MultiplySKBlendMode.multiply

取消NS前缀

NSURL变为URL,NSDate变为Date…

参数label表现一致

在Swift2.2里:函数定义里的第一个参数如果不显式指定label,调用时默认是没有label的:

func someFunc(arg0: String, arg1: String)func anotherFunc(_ arg0: String, arg1: String)//调用时someFunc("first", arg1: "second")anotherFunc("first", arg1: "second")

如上例,两种声明方式效果相同。

而在Swift3中,label的生成方式变得一致,上面的例子会变成:

func someFunc(arg0: String, arg1: String)func anotherFunc(_ arg0: String, arg1: String)//调用时someFunc(arg0: "first", arg1: "second")anotherFunc("first", arg1: "second")

隐式解包可选(ImplicitlyUnwrappedOptional)

SE-0054 的提议寻求减少隐式解包可选类型(ImplicitlyUnwrappedOptional, IUO, 类似于Int!的声明方式)的使用,因为Swift的类型设计本能十分安全,IUO破坏了这种安全性,现在,只可以在以下几个地方使用隐式可选类型:

  • 属性和变量声明
  • 构造器声明
  • 方法声明
  • 角标声明
  • 参数声明 (with the exception of vararg parameters, 这里不太明白,欢迎指导)

在使用中IUO的行为也有改变↓

func f() -> Int! { return 3 } // f: () -> Int?, has IUO attributelet x1 = f() // succeeds; x1: Int? = 3let x2: Int? = f() // succeeds; x2: Int? = .some(3)let x3: Int! = f() // succeeds; x3: Int? = .some(3), has IUO attributelet x4: Int = f() // succeeds; x4: Int = 3let a1 = [f()] // succeeds; a: [Int?] = [.some(3)]let a2: [Int!] = [f()] // illegal, nested IUO typelet a3: [Int] = [f()] // succeeds; a: [Int] = [3]func g() -> Int! { return nil } // f: () -> Int?, has IUO attributelet y1 = g() // succeeds; y1: Int? = .nonelet y2: Int? = g() // succeeds; y2: Int? = .nonelet y3: Int! = g() // succeeds; y3: Int? = .none, has IUO attributelet y4: Int = g() // trapslet b1 = [g()] // succeeds; b: [Int?] = [.none]let b2: [Int!] = [g()] // illegal, nested IUO typelet b3: [Int] = [g()] // trapsfunc p<T>(x: T) { print(x) }p(f()) // prints "Optional(3)"; p is instantiated with T = Int?if let x5 = f() {  // executes, with x5: Int = 3}if let y5 = g() {  // does not execute}

类方法

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

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

去掉了C风格的For循环

for(var i = 0; i < 10; i++)

这个不提的话我想大部分用Swift的人都不会注意到吧。

去掉了柯里化语法

因为这个语法不容易理解,所以去掉了。

去掉了++ --语法

Swift Package Manager

新的Swift包管理器类似于npm这种三方代码的包管理器,对Swift的平台化很有帮助,也许以后的iOS开发者不会再用Cocoapods管理Swift依赖,而是用spm,spm甚至能跨多个平台管理代码,结合Swift最近在各种平台上疯狂移植的新闻。能开发客户端,能写脚本,服务端的Swift库也已经有了好几个,感觉Swift就要变成一个全能的语言了。。

要上天了…

                                        杏树林研发 王儒林
1 0
原创粉丝点击