GeekBand

WWDC15 What's New in Swift

2015-07-18  本文已影响72人  d30d9e0626b0

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

1. Fundamentals

Adoption of new features and best practices:

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<Person,String> {
    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

Detailed, recoverable errors

Logic errors

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 
}
上一篇 下一篇

猜你喜欢

热点阅读