gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:03:15 28 4
gpt4 key购买 nike

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

最佳答案

根据 Swift 中 CocoaAsyncSocket 框架的使用方式,函数 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com