swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.31k stars 10.34k forks source link

[SR-9655] convenience init? with try fails #52099

Open swift-ci opened 5 years ago

swift-ci commented 5 years ago
Previous ID SR-9655
Radar None
Original Reporter JaydenIrwin (JIRA User)
Type Bug
Environment Xcode Version 10.1 (10B61) Swift 4.2
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Compiler | |Labels | Bug | |Assignee | None | |Priority | Medium | md5: b1c569d64f009bc2ffadde607b2f2cf4

Issue Description:

It seems like there is an issue here, but I could be wrong. I'm not sure if the problem is with Swift, or just AVKit, or maybe this is somehow intended behaviour.

I have 2 almost identical pieces of code, but the static function creates a AVAudioPlayer correctly (it will play sounds), while the convenience init version does not work (still runs without error though).

Here is the working version:

static func make(resource: Resource) -> AVAudioPlayer? {
        if let url = Bundle.main.url(forResource: resource.rawValue, withExtension: "wav") {
            do {
                return try self.init(contentsOf: url)
            } catch {
                print("Failed to load sound.")
            }
        }
        return nil
    }

And this doesn't work:

convenience init?(resource: Resource) {
        if let url = Bundle.main.url(forResource: resource.rawValue, withExtension: "wav") {
            do {
                try self.init(contentsOf: url)
            } catch {
                print("Failed to load sound.")
            }
        }
        return nil
    }
belkadan commented 5 years ago

When you say "still runs without error", do you mean it prints the "Failed to load sound." message but doesn't crash, or do you mean it creates an AVAudioPlayer but the resulting object doesn't play anything?

Any chance you can provide a self-contained project? We can try too but that'll increase the chances that we're looking at the same issue you're seeing.

swift-ci commented 5 years ago

Comment by Jayden Irwin (JIRA)

It does not print anything. And the init? returns nil.

Strangely, I just tried adding print statements all over in the init? and none of them print. Not even when print() is the first statement.