Jaxkr
Jaxkr

Reputation: 1293

Why do I need to unwrap this variable?

import SpriteKit

let NumOrientations: UInt32 = 4

enum Orientation: Int, Printable {
case Zero = 0, Ninety, OneEighty, TwoSeventy

var description: String {
    switch self {
        case .Zero:
            return "0"
        case .Ninety:
            return "90"
        case .OneEighty:
            return "180"
        case .TwoSeventy:
            return "270"
    }
}

static func random() -> Orientation {
    return Orientation(rawValue: Int(arc4random_uniform(NumOrientations)))!
}
}

I am new to swift, but I have a lot of programming experience. However, I've never encountered anything like the variable "wrapping" when dealing with unknowns in Swift.

I have the static function random, which returns an Orientation. There is NOTHING optional about the Orientation class. However, I have to use an exclamation point on the return statement in the random function.

Why is this? Excuse my complete lack of knowledge about swift.

Upvotes: 3

Views: 76

Answers (1)

Sulthan
Sulthan

Reputation: 130191

Well, obviously the initializer can fail. Let's assume:

Orientation(rawValue: 10)

This won't find a value in your enum, so what do you expect it to return? It will return nil. That means the return value must be an optional because nil can be returned.

This is explicitly mentioned in Swift Language Guide, Enumerations, Initializing from a Raw Value:

NOTE

The raw value initializer is a failable initializer, because not every raw value will return an enumeration member. For more information, see Failable Initializers.

However, in this case (method random) you are sure that a nil won't be returned, so the best solution is to unwrap the optional before returning it from random.

Upvotes: 5

Related Questions