Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • by replacing throwable initialiser (init... -> throws) with failable one (init?)
  • giving up on subclassing from NSObject

Yet this way I will:

  • loose information about an error causing the exception,
  • have to make instances of FooEven optionals and / or handle many: if let fooEven = FooEven.init() {...} statements
  • ... or I will not be able to use it in existing Objective-C code:

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?

like image 509
Lukasz Avatar asked Oct 18 '22 09:10

Lukasz


2 Answers

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

like image 195
Daniel Inoa Avatar answered Nov 01 '22 07:11

Daniel Inoa


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.

like image 33
Jim Avatar answered Nov 01 '22 07:11

Jim