简体   繁体   English

快速访问按类型枚举

[英]Swift- access enumeration by type

I've got an enum in Swift. 我在Swift中有一个枚举。 It's kind of like 有点像

enum LegalArgs {
    case AsString(String)
    case AsBool(Bool)
    ... etc
}

I want to access this enum conditionally by type . 我想按类型有条件地访问此枚举。 So if I have an instance of LegalArgs, I can pass T and get back a T? 因此,如果我有一个LegalArgs实例,我可以传递T并取回T吗? if the instance was of that type. 如果实例属于该类型。 Otherwise I will have to duplicate a bunch of code for different cases. 否则,我将不得不针对不同情况复制一堆代码。

My current code looks a bit like this: 我当前的代码看起来像这样:

String? maybeAsString(arg: LegalArgs) {
    switch arg {
    case .AsString(let str):
        return str;
    default:
        return nil;
    }
}

The problem is that I've got to duplicate this function for every case in the enum. 问题是我必须为枚举中的每种情况复制此函数。

You can use a generic asType function: 您可以使用通用的asType函数:

enum LegalArgs {
    case AsString(String)
    case AsBool(Bool)
    case AsNumber(Int)

    func asType<T>(type: T.Type) -> T? {
        switch self {
        case AsString(let str): return str as? T
        case AsBool(let bol): return bol as? T
        case AsNumber(let num): return num as? T
        }
    }
}

// usage
LegalArgs.AsBool(true).asType(Bool.self) // true
LegalArgs.AsBool(true).asType(String.self) // nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM