Lukasz
Lukasz

Reputation: 19916

How to bridge throwable Swift initialiser with Objective-C code?

Let's say we have a Swift class with an initializer which can throw an error. This class must be used in Objective-C codebase (NSObject subclass):

import Foundation

enum EvenError : ErrorType {
    case NonEvenNumber
}

class FooEven : NSObject {
    var evenNumber : UInt

    init(evenNumber: UInt) throws {
        guard evenNumber % 2 == 0 else {
            throw EvenError.NonEvenNumber
        }
        self.evenNumber = evenNumber
    }
}

Produces compilation warning:

<unknown>:0: warning: no calls to throwing functions occur within 'try' expression

I can work around this warning in 2 ways:

Yet this way I will:

enter image description here

None of the above satisfies my needs / requirements.

Is there an other way to remove that warning without loosing information about the error?

Upvotes: 5

Views: 663

Answers (2)

Jim
Jim

Reputation: 73966

This is a bug in the Swift compiler and is fixed in Xcode 8. When you upgrade Xcode, this warning will go away.

In the meantime, you can call super.init() at the end of your initialiser and this will also make the warning go away.

Upvotes: 1

Daniel Inoa
Daniel Inoa

Reputation: 51

Another workaround is to add a throwing convenience initializer that calls your non-throwing designated initializer.

Upvotes: 2

Related Questions