[英]Get associated value from enumeration without switch/case
I've got an enumeration with a few different cases which are different types, eg我有一些不同类型的不同案例的枚举,例如
enum X {
case AsInt(Int)
case AsDouble(Double)
}
I can switch
on these just fine to get the underlying value back out.我可以
switch
这些就好获得潜在价值退了出去。 However, the switch
statement is highly annoying with trying to make me execute some code for the other cases that I simply don't care about.然而,
switch
语句非常烦人,它试图让我为我根本不关心的其他情况执行一些代码。 For example, right now I have something like例如,现在我有类似的东西
func AsInt(x: X) -> Int? {
switch x {
case AsInt(let num):
return num;
default:
return nil;
}
}
This works but it's pretty tedious always having to reference this method and having to write a new one for each case of each enumeration.这很有效,但总是必须引用此方法并且必须为每个枚举的每个案例编写一个新方法,这非常乏味。 What I'm looking for is how to simply attempt to cast a value of type
X
to one of the cases, like我正在寻找的是如何简单地尝试将
X
类型的值转换为其中一种情况,例如
var object: X = func();
let value = obj as? Int;
if value {
// do shit
}
How can I simply check for a case without having to enumerate all of the cases about which I don't care and execute some non-statement for them?我怎样才能简单地检查一个案例而不必列举所有我不关心的案例并为他们执行一些非声明?
Bonus points for any solution that can declare value
as part of the conditional instead of polluting the scope.任何可以将
value
声明为条件的一部分而不是污染范围的解决方案的奖励积分。
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
if case
解决方案By having let
outside:通过
let
外面:
var asInt: Int? {
if case let .asInt(value) = self {
return value
}
return nil
}
By having let
inside:通过
let
里面:
var asInt: Int? {
if case .asInt(let value) = self {
return value
}
return nil
}
guard case
guard case
解决方案By having let
outside:通过
let
外面:
var asInt: Int? {
guard case let .asInt(value) = self else {
return nil
}
return value
}
By having let
inside:通过
let
里面:
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.最后一个是我个人最喜欢的四种解决方案的语法。
As of Swift 2 (Xcode 7) this is possible with if/case
and pattern matching:从 Swift 2 (Xcode 7) 开始,这可以通过
if/case
和模式匹配实现:
let x : X = ...
if case let .AsInt(num) = x {
print(num)
}
The scope of num
is restricted to the if-statement. num
的范围仅限于 if 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.