无法转换期望参数类型GTLServiceCompletionHandler的值

时间:2016-10-11 17:17:31

标签: ios google-app-engine swift3 swift2.3

我在Swift 2.3中编写了我的应用程序。使用Google Cloud AppEngine。现在我升级到xCode8.0并需要将我的应用程序转换为Swift 3.0。以下代码在Swift 2.3中是正确的。但它在Swift 3.0中是错误的。任何帮助,将不胜感激! 问题: 无法转换类型'的值(GTLServiceTicket!,GTLObject!,NSError!) - > Void'到预期的参数类型'GTLServiceCompletionHandler!'

func sendRequest() -> GTLServiceTicket? {
    if self.query != nil && shouldSend {
        self.ticket = appService.executeQuery(query!, completionHandler: {
            (ticket: GTLServiceTicket!, object: AnyObject!, error: NSError!) -> Void in
            if error != nil {
                for handler in self.onFailure {
                    handler(ticket, error)
                }
            } else {
                for handler in self.onSuccess {
                    handler(ticket, object)
                }
            }
        })
    }
    return ticket
}

2 个答案:

答案 0 :(得分:0)

如果您跳转到#Swift 3.0 #Xcode 8

,您需要对代码进行一些更改

要记住的事情: -

  • NS已从大多数地方删除 例如NSError已成为Error

  • 现在,来自objective-c的id参数将在swift3中具有类型Any

所以回到这个问题, 以前,如果objective-c代码中的参数没有可空属性(如nonnull或nullable),Swift会将其转换为!使它们不可选(强制展开)。现在转换它?使它们成为可选的这就是你收到错误的原因。完成处理程序将变为:

func sendRequest() -> GTLServiceTicket? { if self.query != nil && shouldSend { self.ticket = appService.executeQuery(query!, completionHandler: { (ticket: GTLServiceTicket?, object: Any?, error: Error?) -> Void in if error != nil { for handler in self.onFailure { handler(ticket, error) } } else { for handler in self.onSuccess { handler(ticket, object) } } }) } return ticket }

答案 1 :(得分:0)

感谢您的回答! 我试过了。以下两个代码正在运行。所有人都需要添加" as Optional' NSError'"和" as Optional' AnyObject'"

1

func sendRequest() -> GTLServiceTicket? {
    if self.query != nil && shouldSend {
        self.ticket = appService.executeQuery(query!, completionHandler: {
            (ticket: GTLServiceTicket?, object: Any?, error: Error?) -> Void in
            if error != nil {
                for handler in self.onFailure {
                    handler(ticket, error as Optional<NSError>)
                }
            } else {
                for handler in self.onSuccess {
                    handler(ticket, object as Optional<AnyObject>)
                }
            }
        })
    }
    return ticket
}

2

func sendRequest() -> GTLServiceTicket? {
    if self.query != nil && shouldSend {
        self.ticket = appService.executeQuery(query!) { ticket, object, error in
            if error != nil {
                for handler in self.onFailure {
                    handler(ticket, error as Optional<NSError>)
                }
            } else {
                for handler in self.onSuccess {
                    handler(ticket, object as Optional<AnyObject>)
                }
            }
        }
    }
    return ticket
}