🌉

エラーが発生するObjective-CのメソッドをSwiftからアクセスするのにtryを使うかどうか

に公開

Objective-Cのエラー発生メソッドの中には、Swiftからアクセスするときに try を使ってアクセスするものがある。

Objective-C側

- (BOOL)methodA:(NSError **)error;
- (BOOL)methodB:(NSInteger)arg1 error:(NSError **)error;
- (BOOL)methodC:(NSError **)error arg1:(NSInteger)arg1;
- (NSInteger)methodD:(NSError **)error;
- (NSInteger)methodE:(NSInteger)arg1 error:(NSError **)error;
- (NSInteger)methodF:(NSError **)error arg1:(NSInteger)arg1;

Swift側

    let myData = MyData()
    
    var error: NSError? = nil;
    
    do {
        try myData.methodA()
        try myData.methodB(1)
        myData.methodC(&error, arg1: 1)
    } catch {
        
    }
    
    myData.methodD(&error)
    myData.methodE(1, error: &error)
    myData.methodF(&error, arg1: 1)

結論

Objective-Cで、

  • 戻り値が BOOL
  • 引数の最後が (NSError **)

のものは Swiftからはtry使用系のメソッドとしてアクセスする。

感想

最終引数が (NSError **) 戻り値が BOOL のものは、その BOOL はエラーの発生の有無を表していると 強制的に解釈される

Discussion