Logan Logan - 6 months ago 32
Swift Question

Unwrap an Enum Tuple outside of a Switch in Swift

So one of the cool new features in Swift is more advanced

enum
s and the possibility to associate more complex data. For example, I could do something like this:

enum Location {
case GeoPoint(latitude: Double, longitude: Double)
case Address(address: String)
}

var address = Location.Address(address: "1234 Fake St, Fakesville TN, 41525")
var geoPoint = Location.GeoPoint(latitude: 42.342, longitude: -32.998)

// address or geoPoint
switch address {
case .Address(let addressStr):
// Unwrapped value as 'addressStr'
println("Address: \(addressStr)")
case .GeoPoint(let latitude, let longitude):
// Unwrapped values as 'latitude' and 'longitude'
println("lat: \(latitude) long: \(longitude)")
}


Is it possible to unwrap these inner values outside of a
switch
statement? Something like:

var addressStr = address.0


Why?

I don't have a good reason, I'm just experimenting with the language.

Answer

I don't think it's possible, because an enum variable is not guaranteed to be a case with those inner values. You could add a computed property that unwraps it for you:

enum Location {

    var address: String? {
    get {
        switch self {
        case .Address(let address)
            return address
        default:
            return nil
        }
    }
    }

    case GeoPoint(latitude: Double, longitude: Double)
    case Address(address: String)
}

Then you can do:

var addressStr = address.address