Swift enum has no member named 'rawValue' when declaring variable as optional
I am looking at Swift Programming Language and I am facing a problem, I cannot distinguish if this is a Lauguage problem or not (I am using Xcode Version 6.1 (6A1052c)):
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five
func simpleDescription() -> String {
switch self {
case .Ace: return "Ace"
default: return String(self.rawValue)
}
}
}
var rank: Rank?
rank = Rank(rawValue: 2)
println(rank.rawValue)
on the last line, it throws an error: 'Rank?' does not have a member named
rawValue ,,
but if you declare a variable of type var rank: Rank
and change rank = Rank(rawValue: 2)
to rank = Rank(rawValue: 2)!
, it can get through without an error.
source to share
Initiating an enum from rawValue returns an optional from that enum Rank?
in your case. To access the properties of an optional enumeration, you need to expand it to get Rank
.
var rank: Rank?
rank = Rank(rawValue: 2)
if(rank != nil){
println(rank!.rawValue)
}
You can also assign Rank Rank
instead ofRank?
var rank: Rank
rank = Rank(rawValue: 2)! //make sure you know this will always return a Rank. If it nil your program will crash
println(rank.rawValue)
source to share