Xcode 3.2 swift shows error with the convenient initializer

Hi!


So I have this code



    convenience init(theme: String) {
        let soundFile = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(theme, ofType: "m4a")!)
        do {
            try self.init(contentsOfURL: soundFile)
        }
        catch let error as NSError {
            print("Sound engine failed: \(error.localizedDescription)")
            return
        }
    }


It was OK before the latest beta. Now it says: 'self' used inside 'catch' block reachable from self.init call.


I see that self.init throws an excepition and I see I should handle it. But when I try I get this error. And it makes no sence to me: the self is inside try block, not inside catch block. Does anybody can tell me what's wrong and how can I make an convenience init of the throwable self.init? Thank you!

UPD. I mean Xcode 7.3 beta 2, not Xcode 3.2 🙂

What class do you try to inherit?

AVAudioPlayer

Accepted Answer

OK, I can reproduce the issue, and find why you get the error.

In your code above, if this line:

            try self.init(contentsOfURL: soundFile)

throws an error, that means self.init() has failed and the initialization procedure has not completed yet.

But you are trying to normally finish your convenience initializer, with `return`.


Thus, this works:

    convenience init(theme: String) {
        let soundFile = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(theme, ofType: "m4a")!)
        do {
            try self.init(contentsOfURL: soundFile)
        }
        catch let error as NSError {
            fatalError("Sound engine failed: \(error.localizedDescription)")
        }
    }

or this:

    convenience init?(theme: String) {
        let soundFile = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(theme, ofType: "m4a")!)
        do {
            try self.init(contentsOfURL: soundFile)
        }
        catch let error as NSError {
            print("Sound engine failed: \(error.localizedDescription)")
            return nil
        }
    }

or simply:

    convenience init(theme: String) throws {
        let soundFile = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(theme, ofType: "m4a")!)
        try self.init(contentsOfURL: soundFile)
    }


Maybe this change is affecting:

Inside a class, a designated initializer that is either failable (init?()) or throwing (init() throws) is allowed to exit before initializing all stored properties and calling super.init().

(https://developer.apple.com/xcode7.3-beta-release-notes)


(EDIT: Removed unneeded `?` form `throws` case.)

Thank you very much indeed!

Okay, this helped me too, thank you. It's me or the message is completely obscure ?

Xcode 3.2 swift shows error with the convenient initializer
 
 
Q