快速枚举中关联值和原始值之间的差异 [英] Difference between associated and raw values in swift enumerations

查看:32
本文介绍了快速枚举中关联值和原始值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 枚举同时具有关联值和原始值.但是我不清楚这些值的用例.因此,如果有人能解释关联值和原始值之间的区别,我将不胜感激,举个例子会很有帮助.

Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference between the associated and raw values, an example would be very helpful.

推荐答案

原始值适用于枚举中的每个案例都由编译时设置值表示的情况.类似于常量,即

Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e.

let A = 0
let B = 1

类似于:

enum E: Int {
    case A  // if you don't specify, IntegerLiteralConvertible-based enums start at 0
    case B
}

所以,A 有一个固定的原始值 0B1 等在编译时设置.它们都必须是相同的类型(原始值的类型适用于整个枚举,而不是每个单独的案例).它们只能是文字可转换的字符串、字符或数字.而且它们都必须不同(没有两个枚举可以具有相同的原始值).

So, A has a fixed raw value of 0, B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case). They can only be literal-convertible strings, characters or numbers. And they all have to be distinct (no two enums can have the same raw value).

关联值更像是变量,与枚举案例中的一个相关联:

Associated values are more like variables, associated with one of the enumeration cases:

enum E {
    case A(Int)
    case B
    case C(String)
}

这里,A 现在有一个关联的 Int 可以保存任何整数值.B 另一方面,没有关联的值.而C 有一个关联的String.关联类型可以是任何类型,而不仅仅是字符串或数字.

Here, A now has an associated Int that can hold any integer value. B on the other hand, has no associated value. And C has an associated String. Associated types can be of any type, not just strings or numbers.

E 类型的任何给定值将只保存一个关联类型,即如果枚举是 A 则为 Int,如果枚举是 C,则为 String.它只需要足够的空间来容纳两者中较大的一个.像这样的类型有时被称为有区别的联合"——联合是一个可以保存多种不同类型的变量,但你知道(从枚举的情况下)它保存的是哪一种.

Any given value of type E will only ever hold one of the associated types, i.e. either an Int if the enum is an A, or a String if the enum is a C. It only needs enough space for the bigger of the two. Types like this are sometimes referred to as "discriminated unions" – a union being a variable that can hold multiple different types, but you know (from the enum case) which one it is holding.

它们甚至可以是通用的.其中最常见的例子是Optional,它的定义如下:

They can even be generic. The most common example of which is Optional, which is defined like this:

enum Optional<T> {
    case .Some(T)
    case .None
}

这篇关于快速枚举中关联值和原始值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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