WasimSafdar
WasimSafdar

Reputation: 1132

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 init?(rawvalue:) 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

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)
        }

    }
}

Upvotes: 0

Views: 2969

Answers (4)

Palani Krishnan
Palani Krishnan

Reputation: 11

enum OptionalValues<T>{
   case None
   case Some(T)
}
var possibleInteger:
OptionalValue<Int>=.None
possibleInteger = .Some(100)

Upvotes: 0

Jason
Jason

Reputation: 634

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!

Upvotes: 1

Avt
Avt

Reputation: 17053

Use init?(rawvalue:) initializer:

let enumValue1 = Rank(rawValue: 100)
print(enumValue1) 
// will print nil because raw value is too big

let enumValue2 = Rank(rawValue: 6)
print(enumValue) 
// will print `Optional(ACNotificationsDemo.Rank.six)`

Upvotes: 1

pbodsk
pbodsk

Reputation: 6876

As you can see here:

enum Rank: Int

"your" Rank enums raw value must be of type Int.

Therefore, to create a new Rank element with ace value, you would write:

let ace = Rank(rawValue: 1)

To create a queen you would write:

let queen = Rank(rawValue: 12)

Notice also that the Rank init returns an optional. This means that if you give it an invalid Int value, you will get nil in return.

For instance:

let notValid = Rank(rawValue: 100) //gives you nil in return

Hope that helps you.

Upvotes: 2

Related Questions