Reputation: 21966
I'm using Xcode 6's playground to try out enums in Swift:
enum Rank: String
{
case One = "One", Two="Two"
init(rawValue : String)
{
self.rawValue = rawValue
}
}
I want to override init so that the enum can be initialized using it's rawValue as argument. But I get an error:
But according to the Apple's Swift guide my code should be correct.
Upvotes: 13
Views: 12553
Reputation: 154513
Martin's answer is completely right.
Here is a different view that more directly answers your question.
In Xcode 6.0, an enum
doesn't have a rawValue
property. rawValue
was added in Xcode 6.1 but note that it is a read-only computed property, so you can't assign to it in Xcode 6.1 either.
In Xcode 6.1, it is unnecessary to implement an initializer that takes a rawValue
because that has already been provided natively by the language. If you were trying to imitate that behavior in Xcode 6.0, then you might try something like:
enum Rank: String
{
case One = "One", Two="Two"
init(rawValue : String)
{
self = Rank.fromRaw(rawValue)
}
}
but the problem with this is that fromRaw
returns an optional enum value because the rawValue
string might correspond to any enum value.
So what do you do at this point? You could add a !
to force unwrap the value:
self = Rank.fromRaw(rawValue)!
but this would crash if you tried to create an enum with an invalid raw value.
You could treat one of the enum values as a default and use the nil coalescing operator ??
to safely unwrap it:
self = Rank.fromRaw(rawValue) ?? One
which would avoid a crash, but would probably lead to unexpected behavior on the part of your program.
What you can't do in Xcode 6.0 is have the init
return an optional value. This capability was added in Xcode 6.1 and it was exactly this new capability that allowed them to change fromRaw()
from a function in Xcode 6.0 to an optional initializer in Xcode 6.1.
Upvotes: 11
Reputation: 539685
The conversion methods between enums and their raw values changed between Xcode 6.0
and Xcode 6.1. The fromRaw()
and toRaw()
method have been replaced by
a (failable) initializer and a rawValue
property:
Xcode 6.0:
// raw value to enum:
if let rank = Rank.fromRaw("One") { }
// enum to raw value:
let str = rank.toRaw()
Xcode 6.1:
// raw value to enum:
if let rank = Rank(rawValue: "One") { }
// enum to raw value:
let str = rank.rawValue
Upvotes: 14