Why do I need to expand 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'm new to swift, but I have a lot of programming experience. However, I've never seen anything like the "wrapping" variable when working with unknowns in Swift.

I have a static function random that returns Orientation. There is no optional about the Orientation class. However, I have to use an exclamation mark for the return statement in the random function.

Why is this? Sorry for my complete lack of knowledge about fast.

+3


source to share


1 answer


Well, obviously, the initializer can fail. Let's pretend that

Orientation(rawValue: 10)

      

This won't find a value in your enum, so you expect it to return? He will return nil

. This means that the return value must be optional as it nil

can be returned.



This is explicitly mentioned in the Swift Language Guide , Enumerations , Initialization with Raw Value>:

Note

The raw value initializer is an error initializer because not every raw value returns an enumeration member. See the Failed Initializers section for more information.

However, in this case (the method random

) you are sure nil

it will not be returned, so the best solution is to unwrap the optional before returning it from random

.

+5


source







All Articles