在我更新 Xcode 7 beta 并将我的 swift 代码转换为 Swift 2 后,我遇到了这两个我无法弄清楚的错误..
Call can throw, but it is not marked with 'try' and the error is not handled
Binary operator '==' cannot be applied to operands of type '()?' and 'Bool'
我的代码在这里。
if self.socket?.connectToHost(host, onPort: port, viaInterface: interfaceName, withTimeout: 10) == true {
// connecting
} else {
// error
let delay = 1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self._connect()
})
}
知道问题出在哪里吗?
快照:
最佳答案
根据 CocoaAsyncSocket 框架在 Swift 中的使用方式,函数 connectToHost:onPort:viaInterface:withTimeout:
没有返回值。相反,它只会抛出。因此,该错误的含义是 Void
(无返回值)不能与 Bool
进行比较。
它在 Swift 中的声明是:
func connectToHost(host: String!, onPort port: UInt16, viaInterface interface: String!, withTimeout timeout: NSTimeInterval) throws
这与它与 Objective-C 一起使用时的声明不同,其中声明是:
- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port withTimeout:(NSTimeInterval)timeout
顺便说一句,在 Objective-C 中,您可以将 nil
视为 bool 值,并将非零值评估为 TRUE
,但这些可能性是从 Swift 中删除是因为它们是常见的错误来源。
要处理错误,需要使用以下形式,称为 do-try-catch。以下是根据您的代码进行调整的示例:
do {
try self.socket?.connectToHost(host, onPort: port, viaInterface: interfaceName, withTimeout: 10)
// connecting
} catch let error as NSError {
// Handle the error here.
let delay = 1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self._connect()
})
}
关于ios - swift 2 : Binary operator '==' cannot be applied to operands of type '()?' and 'Bool' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33591959/