ios - swift 2 : Binary operator '==' cannot be applied to operands of type '()?' and 'Bool'

标签 ios swift swift2 cocoaasyncsocket

在我更新 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()
  })
}

知道问题出在哪里吗?

快照:

enter image description here

最佳答案

根据 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/

相关文章:

c - TCP 连接。如何让客户端只在服务端read()的那一刻发送数据?

ios - 暂时禁用 UITableView 中的删除按钮

ios - 使用pdf图像设置背景

json - 类型 "Any"在从服务器提取数据数组期间在 Swift 3 中没有下标成员

ios - 按下时快速更改按钮背景颜色和图像颜色

ios - 如何使 UIImage View 可点击以转到另一个 View Controller

ios - Firebase 查询 - 查找用户匹配的电子邮件

swift - 创建记录后如何创建结果?

ios - 如何将项目追加到表格或 Collection View 的底部?

Objective-c 代码等于守卫