从没有开关/案例的枚举中获取关联值 [英] Get associated value from enumeration without switch/case

查看:105
本文介绍了从没有开关/案例的枚举中获取关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不同类型的不同情况的枚举,例如

I've got an enumeration with a few different cases which are different types, e.g.

enum X {
    case AsInt(Int)
    case AsDouble(Double)
}

I可以开关在这些都很好,以获得底层的价值。但是,开关语句是非常讨厌的,试图让我执行一些我根本不在乎的其他情况的代码。例如,现在我有一些类似

I can switch on these just fine to get the underlying value back out. 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. For example, right now I have something like

func AsInt(x: X) -> Int? {
    switch x {
    case AsInt(let num):
        return num;
    default:
        return nil;
    }
}

这是有用的,但总是不得不引用这个方法,并且必须为每个枚举的每种情况写一个新的方法。我正在寻找的是如何简单地尝试将一个类型 X 的值投放到其中一种情况,如

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

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?

任何解决方案可以声明 value 作为条件的一部分,而不是污染范围。

Bonus points for any solution that can declare value as part of the conditional instead of polluting the scope.

推荐答案

根据Swift 2(Xcode 7),可以通过 if / case
模式匹配:

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)
}

num 的范围仅限于if-statement。

The scope of num is restricted to the if-statement.

这篇关于从没有开关/案例的枚举中获取关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆