Reputation: 9039
I have read documentation on Swift's failable initializer's but didn't see anything explicit about the normal, non-failable variety. Did I miss something, or are regular initializer not supported for enumerators with raw values, even when there is no possibility that the initializer could fail (since the initializer defers to a default value):
enum FailableSeason : Int {
init?(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
enum ImplicitlyUnwrappedFailableSeason : Int {
init!(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
enum NonFailableSeason : Int {
init(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
let thisWorks = FailableSeason(d: 60)
let thisFails = ImplicitlyUnwrappedFailableSeason(d: 60)
let andThisFails = NonFailableSeason(d: 0)
Note that I broke this into separate enums to make sure that it wasn't a problem of conflicting initializers.
Upvotes: 0
Views: 426
Reputation: 539975
This used to work with Swift 1.1 (Xcode 6.1.1) but fails in Swift 1.2 (Xcode 6.3). It is a bug which has been discussed in the Apple Developer Forum: Swift 1.2 - Initializing Enums.
Two workarounds are given in that discussion: Use the module/app name as a prefix:
let workaround1 = NameOfYourModule.NonFailableSeason(d: 0)
Or call the init method explicitly:
let workaround2 = NonFailableSeason.init(d: 0)
Update: This has been fixed in the Xcode 6.3 beta 2 (6D532l) release.
Upvotes: 1