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

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

问题描述

Swift枚举具有关联值和原始值。但这些价值观的用例对我来说并不清楚。所以我真的很感激任何人可以解释关联和原始值之间的差异,一个例子将是非常有用的。

解决方案

原始值是针对枚举中的每个案例由编译时设置值表示的。类似于常数,即

  let A = 0 
let B = 1

类似于:

 枚举E:Int {
case A //如果你没有指定,IntegerLiteralConvertible的枚举从0开始
case B
}
/ pre>

所以, A 具有固定的原始值 0 B 1 等在编译时设置。它们都必须是相同的类型(原始值的类型是整个枚举,而不是每个单独的情况)。它们只能是字面可转换的字符串,字符或数字。而且它们都必须是 (没有两个枚举可以具有相同的原始值)。



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

 枚举E {
案例A(Int)
case B
case C(String)
}

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



类型 E 的任何给定值只会如果枚举是一个 A ,或$ $ c,则持有其中一个关联类型,即 Int $ c> String 如果枚举是一个 C 。它只需要足够的空间来扩大两者之间的距离。类似这种类型有时被称为歧视联盟 - 一个联合是一个可以容纳多种不同类型的变量,但是你知道(从枚举的情况)它所持有的那个。



他们甚至可以是通用的。最常见的例子是可选,其定义如下:

 枚举可选< T> {
case .Some(T)
case .None
}


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

is similar to:

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

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

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.

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.

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天全站免登陆