Search code examples
swiftenumsswitch-statementletassociated-value

Is there a way in Swift to get an associated value without using a switch statement?


When I have a situation where I already know enum case statement I want to get the associated value of, is there a cleaner way than using a switch statement to pluck out the associated value?

To have to come up with a switch statement, provide multiple cases, or a default case just to extract the associated value is gaudy.

enum CircularReasoning {
    case justPi(pi: Double)
    case pizzaPie(howMany: Int)
}

var piInTheSky : Double 

let whatLogic = CircularReasoning(pi: 3.1415926)

⬇️ 𝘸𝘒𝘯𝘡 𝘡𝘰 𝘒𝘷𝘰π˜ͺπ˜₯ ⬇️ 

switch whatLogic {
    case .justPi(let pi):
        piInTheSky = pi!
    default:
        break
}

Solution

  • You can use if case .<enum_case>(let value) as in TylerP's example, or if case let .<enum_case>(value):

    enum Foo {
        case anInt(Int)
        case aFloat(Float)
    }
    
    let aFoo: Foo = .anInt(9)
    
    // Example of `if case .<enum_case)(let value)` syntax:
    if case .anInt(let aValue) = aFoo {
        print("aFoo = anInt(\(aValue))")
    
    // Example of `if case let .enum_case(value)` syntax:
    } else if case let .aFloat(aValue) = aFoo {
        print("aFoo = aFloat(\(aValue))")
    }
    

    Both work. I'm not sure why the language includes both variants.

    If you only care about one enum type, then either if syntax makes sense to me. If you are dealing with more than one possible enum value then the switch version seems cleaner.