I\'ve got an enumeration with a few different cases which are different types, e.g.
enum X {
case AsInt(Int)
case AsDouble(Double)
}
<
As of Swift 2 (Xcode 7) this is possible with if/case
and
pattern matching:
let x : X = ...
if case let .AsInt(num) = x {
print(num)
}
The scope of num
is restricted to the if-statement.
There are actually multiple ways to do it.
Let's do it by extending your enum with a computed property:
enum X {
case asInt(Int)
case asDouble(Double)
var asInt: Int? {
// ... see below
}
}
if case
By having let
outside:
var asInt: Int? {
if case let .asInt(value) = self {
return value
}
return nil
}
By having let
inside:
var asInt: Int? {
if case .asInt(let value) = self {
return value
}
return nil
}
guard case
By having let
outside:
var asInt: Int? {
guard case let .asInt(value) = self else {
return nil
}
return value
}
By having let
inside:
var asInt: Int? {
guard case .asInt(let value) = self else {
return nil
}
return value
}
The last one is my personal favorite syntax of the four solutions.