Swift compiler erroneously thinks that a property is not initialized at end of init()

Originator:klazuka
Number:rdar://17738432 Date Originated:7/19/2014
Status:Closed Resolved:7/31/2014
Product:Swift Compiler Product Version:Xcode6-beta3 (6A254o)
Classification:bug Reproducible:yes
 
The Swift compiler is easily confused into thinking that a property is not set in an initializer by the time that the initializer returns. For instance:

------------------------------------------------------------

import Foundation

struct Row {
    let a: String = "example"
    let b: String
    let c: String?
}

extension Row {
    init(csv string: String) {
        var didSetB = false
        for (idx, part) in enumerate(string.componentsSeparatedByString(",")) {
            switch idx {
            case 0: self.a = part
            case 1: self.b = part; didSetB = true
            case 2: self.c = part
            default: break
            }
        }
        if !didSetB {
            self.b = "(unknown)"
        }
    }
}

println(Row(csv: "wind,sea,kite"))

------------------------------------------------------------

The Swift compiler reports an error "Variable self.b used before being initialized" at the end of the init(). But clearly there is no possible control flow where `self.b` will not have a value.

Comments

Apple closed the bug report with the following comment:

Engineering has determined that this issue behaves as intended based on the following:

This is our definitive initialization model working as designed. It isn't practical to cover cases like this and similar systems (e.g. Java) have similar limitations. See also: http://en.wikipedia.org/wiki/Definite_assignment_analysis

Still broken in Xcode6-beta4 (6A267n).


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!