5

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?

Lukasz
  • 19,816
  • 17
  • 83
  • 139
  • Can you use a closure that contains an NSError object to capture the error info? I don't know that much about Swift, sorry. – fsb May 10 '16 at 15:34
  • Don't have an answer for you, but did you ever resolve this? Running into the same problem. – chrismanderson Jun 25 '16 at 13:06

2 Answers2

2

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

1

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.

Jim
  • 72,985
  • 14
  • 101
  • 108