instance must be initialized before throwing from an initializer / instance must be initialized before returning nil from an initializer

Originator:stephen.groom
Number:rdar://21744509 Date Originated:09-Jul-2015 02:13 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Swift 2b3
Classification:Other Bug Reproducible:Always
 
If I have a fallible initializer or one which throws on a class with a non-optional property, it is impossible to throw or return nil without setting all the properties first.  Example:
—

func somethingThatThrows() throws { }

class Example {
    init() throws
    {
        do {
            try somethingThatThrows()
        } catch let error {
            throw error
        }
    }
}

—

The above works, but the following two snippets do not:
—

func somethingThatThrows() throws -> String { return "" }

class Example {
    let string: String
    init() throws
    {
        do {
            string = try somethingThatThrows()
        } catch let error {
            throw error
        }
    }
}

—

func somethingThatThrows() throws -> String { return "" }

class Example {
    var string: String
    init?()
    {
        do {
            string = try somethingThatThrows()
        } catch {
            return nil
        }
    }
}

—

I believe that this is a major use case as it is sensible to return nil from init if you were unable to correctly set all properties for some reason

Comments

This is resolved as of Swift 2.2 / Xcode 7.3

Maybe even earlier.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!