NSDateComponentsFormatter claims to return String! with Swift, but returns nil causing fatal error with negative input

Originator:juri.pakaste
Number:rdar://17435110 Date Originated:24-Jun-2014 05:48 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode6-Beta2 (6A216f)
Classification:Crash/Hang/Data Loss Reproducible:Always
 
Summary:
On iOS SDK 8 beta 2, NSDateComponentsFormatter returns nil when given a negative time interval or date components with negative content, but the the Swift return type is String! which causes a fatal error when trying to use as String.

Steps to Reproduce:
Following code:

func testComps() -> String {
    let fmt = NSDateComponentsFormatter()
    fmt.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional;
    fmt.allowedUnits = NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond;

    let comps = NSDateComponents()
    comps.second = -2
    let s = fmt.stringFromDateComponents(comps)
    println("fmt: \(fmt), s: \(s)")
    return s
}

or

func testInterval() -> String {
    let fmt = NSDateComponentsFormatter()
    fmt.unitsStyle = NSDateComponentsFormatterUnitsStyle.Positional;
    fmt.allowedUnits = NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond;

    let s = fmt.stringFromTimeInterval(-2)
    println("fmt: \(fmt), s: \(s)")
    return s
}

Causes “fatal error: Can't unwrap Optional.None”. NSDateComponentsFormatter’s formatting has an undocumented restriction on that it doesn’t support negative times, and if the parameter is negative, it returns nil. The return value is typed String!, however, which implies it should always be non-nil. It should be String?, and that restriction should be documented.

Comments


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!