Chris Lattner 實在是太帥了!
Session 106 - What’s new in swift
Why Swift 2
- Fundamentals: Refine language and tools fundamentals
- Safety: Affordances for writing robust and safe code
- Beauty: Enable expressive libraries and APIs
用更好的語言寫更加安全和漂亮的代碼!
What’s New in Swift 2
- Fundamentals
- Pattern Matching
- Availabilty Checking
- Protocol Extensions
- Error Handling
Fundamentals
-
Enums
enum Animals { case a, b }
-
Associated Values in Enums
enum Either<T1, T2> { case First(T1) case Second(T2) }
-
Recursion Enums
enum Tree<T> { case Leat(T) indirect case Node(Tree, Tree) }
-
do
Statementdo { let a = Animals.Troll ... } // loop repeat { ... }
-
Option Sets
[option1, option2]
-
Defining an Option: Using Protocol-Oriented Programming
struct MyFontSyle : SetOptionSetType
-
-
Functions and Methods
- Consistent Argument Labels
- Duplicate first name
- Underscore to disable name labels
- # argument syntax
- Diagnostics
-
SDK Improvements
- Nullability qualifiers
- Objective-C typed Collections
-
Testing
@testable import MyApp
- Rich Comments
- A Lot More!
Pattern Matching
if-let
Statment- Compound Conditions
-
Early Exits:
guard
Statementguard let name = json["name"] as? String else { return .Second("missing name") } // Compound Condidtions guard let name = json["name"] as? String, let year = json["year"] as? Int else { return .Second("bad input") }
-
Switch
if case .MyEnumCase(let value) = bar() where value != 42 { doSomething(value) }
-
for ... in
Filteringfor value in mySequence where value != "" { doSomething(value) }
Availabilty Checking
- New APIs
- springLoaded
- old:
respondsToSeletor
Method - new: get a diagnostic
-
Example:
if #available(OSX 10.10.3, *) { ... }
Protocol Extensions
- Extensions
-
Old
extension Array { func countIf(match: Element -> Bool) -> Int { var n = 0; for value in self { if match(value) { n++; } } return n } } + Global Functions
-
New
extension CollectionType
-
-
Method
.map().filter()
Error Handling
- Kinds
- Trivial Errors
- Logic Errors
- Detailed, recoverable Errors
- Example
try
Keywordthrows
Keyword-
do-catch
Blockdo { ... } catch let error { ... } catch { fatalError() }
try!
Keyword
-
Enums as Error Types
enum DataError : ErrorType { case MissingName case MissingFile }
-
Defer Actions
defer { delegate?.didEndProcessing() }