WasimSafdar WasimSafdar - 9 months ago 76
Swift Question

How to create enum optional instance

I am leraning Swift 3 from "The Swift Programming Language (Swift 3 beta)". Below is their enum example. In the end of this example, they have written "Use the

to make an instance of enumeration from a raw value". Can anybody tell me, how to make that. Thanks.

enum Rank: Int {

case ace = 1 // Raw value
case two, three, four , five , six, seven, eight, nine, ten
case jack, queen, king

func simpleDescription() -> String{

switch self {
case .ace:

return "ace"

case .jack:

return "jack"

case .queen:

return "queen"

case .king:

return "king"


return String(self.rawValue)



You can create an optional init for an enum like so:

init?(rawValue: String) {
    if rawValue == "ace" {
        self = .ace
    } else {
        return nil

The else handles an invalid / unexpected value in term (this is why the init is an optional initialiser - it may return nil if given an invalid input). Hope this helps!