【问题标题】:How to convert Objective-C code to Swift code - errorhandling ,iOS如何将 Objective-C 代码转换为 Swift 代码 - 错误处理,iOS
【发布时间】:2017-01-16 01:33:32
【问题描述】:

我正在尝试将此文本转换为 swift:

- (void)sendData:(NSData*)data
{
    NSError *error;
    GameKitHelper *gameKitHelper = [GameKitHelper sharedGameKitHelper];

    BOOL success = [gameKitHelper.match
                    sendDataToAllPlayers:data
                    withDataMode:GKMatchSendDataReliable
                    error:&error];

    if (!success) {
        NSLog(@"Error sending data:%@", error.localizedDescription);
        [self matchEnded];
    }
}

现在我已经到这里了:

func sendData(data: NSData) {
    var error: NSError?
    var gameKitHelper = GameKitHelper.sharedGameKitHelper()
    var success = try! gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: GKMatchSendDataReliable)
    if !success {
        print("Error sending data:\(error.localizedDescription)")
        self.matchEnded()
    }
}

但是if (!succes) 给了我一个错误,我在苹果文档上读到 .sendDataToAllPlayers() 的objective-c 版本将返回一个布尔值,但 swift 版本不会。

Apple Documentation - GKMatch

那么我该如何处理错误

【问题讨论】:

  • 如果您查阅文档,您会发现 Swift 方法没有返回布尔值,而是 throws 一个错误。在 Swift 书中查找“错误处理”。

标签: objective-c swift error-handling


【解决方案1】:

如果发生错误,sendDataToAllPlayers 函数会抛出异常。你需要一个 catch 块来处理它:

func sendData(data: NSData) {
    var gameKitHelper = GameKitHelper.sharedGameKitHelper()
    do {
        try gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: .Reliable)
    }
    catch let error as NSError {
        print("Error sending data:\(error.localizedDescription)")
        self.matchEnded()
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多