この記事では「The Swift Programming Language」を1から読んだ感想とか発見を書いてみようと思います。
「The Swift Programming Language」とはSwiftの公式ドキュメントでiBooksや下ページで見る事ができます。
The Swift Programming Language (Swift 2.1): About Swift
読んだ所
今回はDeclarations
という項目を読みました。
The Swift Programming Language (Swift 2.1): Declarations
学んだこと
rethrows構文
rethrows
とは限定的なthrows
です。
下のようにthrows
を持つメソッドを引数にする場合のみ使えます。
func method(function: (Void) throws -> Void) rethrows -> Int { try function() return 1 }
rethrows
とthrows
は引数のメソッドにthrows
がない時に違いが出ます。
rethrows
の場合は引数のメソッドにthrows
がない場合はdo-catchで囲む必要がなくなります。
func method1(function: (Void) throws -> Void) throws -> Int { try function() return 1 } do { try method1({}) } catch {} do { try method1({ _ throws in }) } catch {} // rethrowsを使ったパターン func method2(function: (Void) throws -> Void) rethrows -> Int { try function() return 1 } method2({}) // 引数にthrowsがない場合はdo-catchで囲まなくて良い do { try method2({ _ throws in }) } catch {}
Generics付きのenum
Optional型がそうなのですが、EnumはGenericsを持つことができます。
下のように好きな型で初期化できます。
enum Tree<T> { case Empty case Node(value: T) } Tree.Node(value: 1) Tree.Node(value: "11")