swift - How to create enum optional instance -
i leraning swift 3 "the swift programming language (swift 3 beta)". below enum example. in end of example, have written "use init?(rawvalue:)
make instance of enumeration raw value". can tell me, how make that. thanks.
enum rank: int { case ace = 1 // raw value case two, three, 4 , 5 , six, seven, eight, nine, ten case jack, queen, king init?(rawvalue: int) { self = rawvalue == 1 ? .ace : .jack } func simpledescription() -> string{ switch self { case .ace: return "ace" case .jack: return "jack" case .queen: return "queen" case .king: return "king" default: return string(self.rawvalue) } } }
as can see here:
enum rank: int
"your" rank
enums raw value must of type int
.
therefore, create new rank
element ace
value, write:
let ace = rank(rawvalue: 1)
to create queen write:
let queen = rank(rawvalue: 12)
notice rank
init returns optional. means if give invalid int
value, nil
in return.
for instance:
let notvalid = rank(rawvalue: 100) //gives nil in return
hope helps you.
Comments
Post a Comment