2

After I updated Xcode 7 beta and convert my swift code to Swift 2, I got these two errors that I can't figure out..

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'

My code is here.

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()
  })
}

Any idea what can be the problem?

Snapshot:

enter image description here

Community
  • 1
  • 1
Shoun Moon
  • 23
  • 3

1 Answers1

3

Based on how the CocoaAsyncSocket framework is used in Swift, the function connectToHost:onPort:viaInterface:withTimeout: does not have a return value. Instead it only throws. Therefore, the meaning of the error is that a Void, no return value, cannot be compared to a Bool.

Its declaration in Swift is:

func connectToHost(host: String!, onPort port: UInt16, viaInterface interface: String!, withTimeout timeout: NSTimeInterval) throws

This differs from its declaration when used with Objective-C where the declaration is:

- (BOOL)connectToHost:(NSString *)hostname onPort:(UInt16)port withTimeout:(NSTimeInterval)timeout

As an aside, in Objective-C, you could handle a nil as if it were a boolean along with nonzero values being evaluated as TRUE, but those possibilities were removed from Swift because they are a common source of errors.

To handle the error requires the following form known as do-try-catch. Here is an example adjusted to your code:

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()
    })
}
Daniel Zhang
  • 5,778
  • 2
  • 23
  • 28