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

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

问题描述

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

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

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

我可以很好地switch 以获取底层价值.但是,switch 语句非常烦人,因为它试图让我为我根本不关心的其他情况执行一些代码.例如,现在我有类似

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.

推荐答案

实际上有多种方法可以做到.

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

的解决方案

通过将 let 放在外面:

var asInt: Int? {
    if case let .asInt(value) = self {
        return value
    }
    return nil
}

通过将 let 放在里面:

var asInt: Int? {
    if case .asInt(let value) = self {
        return value
    }
    return nil
}

guard case 的解决方案

通过将 let 放在外面:

Solutions with guard case

By having let outside:

var asInt: Int? {
    guard case let .asInt(value) = self else {
        return nil
    }
    return value
}

通过将 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.

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

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