1

I have a project in which I am trying to use Swift for the new modules. For one of the new class, I am using an existing method of an Objective-C class in Swift 3.2.

Following is the signature of the method,

- (BOOL)canLoginWithUsername:(NSString *)username password:(NSString *)password error:(NSError **)error

I am trying to use this method in swift as,

    if try loginLogicHandler.canLogin(withUsername: usernameValue, password: passwordValue) as Bool {

}

However, I am getting a compiler error as

Cannot convert value of type () to type 'Bool' in coercion

What should I do to make this working?

Could anyone suggest how to fix this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Have a look at this link it might help: [https://stackoverflow.com/questions/25561096/cleanly-converting-an-objective-c-boolean-to-a-swift-bool](https://stackoverflow.com/questions/25561096/cleanly-converting-an-objective-c-boolean-to-a-swift-bool) –  Oct 08 '17 at 01:03
  • Compare https://stackoverflow.com/q/45565960/2976878 – Hamish Oct 08 '17 at 01:04

1 Answers1

4

Objective-C methods that return BOOL and return an NSError by reference are exposed to Swift as methods that use the try/catch error-handling mechanism, and return Void. If you look at the generated interface, you'll probably see that it looks something like this:

func canLogin(withUsername: String, password: String) throws // notice no return type

If the Objective-C method fails, it returns NO, and populates the error pointer, and Swift then throws that error. So, you need to use try and catch:

do {
    try loginLogicHandler.canLogin(with: bla, and: bla)

    // if canLogin returned YES, you get here
} catch {
    // if canLogin returned NO, you get here
}

Alternately, you can use try?. This one's kind of weird; you'll get an optional Void, so you'll get Void if the method succeeds, or nil if it fails:

if (try? loginLogicHandler.canLogin(with: bla, and: bla)) != nil {
    // the method returned YES
}
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60