WWDC15 What's New in Swift 笔记

原视频地址点我,不知道为什么本文在 Hexo 中,会造成其停止工作。折腾半天,重装 Hexo,Time Machine 还原系统,均失败,最后不断删除 post,才对位到问题。

1. Fundamentals

  • Diagnostics
  • New Warnings
  • SDK Improvements

Adoption of new features and best practices:

  • Nullability qualifiers

  • Objective-C typed collections

  • NS_ENUM, NS_OPTIONS, instancetype, @property, etc

  • Unit Testing
    Your code is now built in a “compile for testing” build mode:
    Unit tests use
    @testable
    import MyApp
    public and internal symbols are now available
    No behavior change for release builds:
    Same optimizations
    Same insurance against symbol collisions

2. Pattern Matching

Pattern Matching with “if case”

switch bar() {

case .MyEnumCase(let value):where value != 42:
  doThing(value)
default: break
}

if case .MyEnumCase(let value) = bar() where value != 42 {
    doThing(value)
}

“for ... in” Filtering

for value in mySequence {
    if value != "" {
        doThing(value)
    }
}
for value in mySequence where value != "" {
    doThing(value)
}
for case .MyEnumCase(let value) in enumValues {
    doThing(value)
}

“if let” Statement: Compound Conditions

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let dest = segue.destinationViewController as? BlogViewController
       let blogIndex = tableView.indexPathForSelectedRow()?.row
       where segue.identifier == blogSegueIdentifier {

“guard” Statement: Compound Conditions

func process(json: AnyObject) -> Either {
    guard let name = json["name"] as? String,
          let year = json["year"] as? Int else
        return .Second(“bad input”)
    }
    let person = processPerson(name, year)
    return .First(person)
}

3. Availability Checking

The Better Approach

@IBOutlet var dropButton: NSButton!
override func awakeFromNib() {
    if #available(OSX 10.10.3, *) {
        dropButton.springLoaded = true
  } 
}

4. Protocol Extensions

Methodification

Global generic algorithms are becoming methods

Swift 1:
let x = filter(map(numbers) { $0 * 3 }) { $0 >= 0 }
Swift 2:
let x = numbers.map { $0 * 3 }.filter { $0 >= 0 }

5. Error Handling

Kinds of Error

Trivial errors

  • Int(someString)

Detailed, recoverable errors

  • File not found
  • Network failure
  • User cancellation

Logic errors

  • Assertions, overflows, NSException, etc.

Works Great with Cocoa

Swift 1:

extension NSData {
  class func bookmarkDataWithContentsOfURL(bookmarkFileURL: NSURL,

-> NSData? 
}

Swift 2:

extension NSData {
  class func bookmarkDataWithContentsOfURL(bookmarkFileURL: NSURL) throws
-> NSData 
}

你可能感兴趣的:(WWDC15 What's New in Swift 笔记)