关联值和原始值可以在Swift枚举中共存吗? [英] Can associated values and raw values coexist in Swift enumeration?

查看:173
本文介绍了关联值和原始值可以在Swift枚举中共存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift书中有一些示例分别说明了关联值和原始值,有没有办法同时定义具有两个功能的枚举?

There are examples on Swift book demonstrating associated values and raw values separately, is there a way to define enums with the two features together?

我试图结合它们,但出现错误:

I have tried to combine them, but got errors:

enum Barcode :String {
    case UPCA(Int, Int, Int) = "Order 1" // Enum with raw type cannot have cases with arguments
    case QRCode(String) = "Order 2" // Enum with raw type cannot have cases with arguments
}


推荐答案

是的,这是可能的。枚举可以包含关联值和原始值。 ( Swift 5& 4

Yes this is possible. An enum may contain both associated values and raw values. (Swift 5 & 4)

您的问题代码是您对 RawRepresentable 定义关联类型使用简写表示法。

The issue with your code is that you are using the shorthand notation for RawRepresentable and defining associated types.

让我们看看如何分别定义它们:

Let's look at how to define these separately:

1) RawRepresentable (简写表示法):

1) RawRepresentable (shorthand notation):

enum Barcode: String {
    case UPCA   = "order 1"
    case QRCode = "order 2"
}

2)关联类型:

enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

每一个都很棒,但是如果您的代码片段显示了两者都需要的话。

Each of these is great, but what if you need both as your code snippet shows.

用关联值定义枚举,然后实现对 RawRepresentable 的一致性单独扩展名(即不是usin

Define the enum with associated values and then implement conformance to RawRepresentable separately in an extension (i.e. not using shorthand notation).

示例:

enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

extension Barcode: RawRepresentable {

    public typealias RawValue = String

    /// Failable Initalizer
    public init?(rawValue: RawValue) {
        switch rawValue {
        case "Order 1":  self = .UPCA(1,1,1) 
        case "Order 2":  self = .QRCode("foo")
        default:
            return nil
        } 
    }

    /// Backing raw value
    public var rawValue: RawValue {
        switch self {
        case .UPCA:     return "Order 1"
        case .QRCode:   return "Order 2"
        }
    }

}

次要详细信息

在此解决方案中,默认值为关联值,例如从rawValue参数构造枚举时,必须提供 .UPCA(1,1,1)。您可以看中并使用关联的类型作为后备原始值的一部分-功能更强大,但会增加一些复杂性。

In this solution, defaults for the associated values, e.g. .UPCA(1,1,1) must be supplied when constructing the enum from the rawValue argument. You can get fancy and use the associated types as part of the backing raw value — which is more powerful, but adds some complexity.

参考

有关该主题的更多信息,请参见奥莱·贝格曼(Ole Begemann)的出色写作。

For more info on the topic see Ole Begemann's excellent write up.

这篇关于关联值和原始值可以在Swift枚举中共存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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