Throwing method cannot be a member of an @objc protocol because it returns a value of type 'Bool'
Asked Answered
M

1

6

I get following error:

Throwing method cannot be a member of an @objc protocol because it returns a value of type 'Bool'; return 'Void' or a type that bridges to an Objective-C class

When defining Swift protocol which also needs to be bridged to Objective-C:

@objc public protocol Saving {

    func save() throws -> Bool
}

Is there an other way to define Swift method which can return Bool, potentially throw an error and be Objetive-C compatible?

Macrophage answered 8/3, 2016 at 14:34 Comment(3)
Why would you want to return a Bool and throw? Success/Failure is indicated either by returning true/false or by throwing. – func save() throws would be translated to Objective-C as - (BOOL)saveAndReturnError:(NSError **)error;Libration
"Using Swift with Cocoa and Objective-C" document is not clear if Swift function throwing error will be converted to the Objective-C method returning BOOL.Macrophage
I actually tested it now and looked at the head files generated by Swift and you are right.Macrophage
M
6

As indicated in the comments, the following in Swift:

func save() throws

will be translated into:

(BOOL)saveAndReturnError:(NSError **)error

in Objective-C. Which explains the limitation.

I know that in the save() example, it might not make much sense to return a Bool as well as throwing, but I disagree with the comment about it not making sense at all. There might be other use cases where it makes sense. Fx. the inverse example; loading Bool's by using an identifer. Loading a Bool might return true/false or throw if loading fails, fx. if the identifier was not found when trying to load.

However unfortunately we cannot do this because of how Swift and Objective-C is being bridged.

Mogador answered 23/3, 2016 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.