Swift枚举字节表示是什么? [英] What is Swift enum byte representation?

查看:78
本文介绍了Swift枚举字节表示是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举:

enum Enum: UInt8 
{
  case A = 0x00
  case B = 0x01
  case C = 0x10
}

我使用以下代码将其转换为 NSData

I use the following code to convert it to NSData:

var value = Enum.C
let data = NSData(bytes: &value, length: 1)

自然,我希望数据包含 0x10 ,但是,它包含 0x02

Naturally, I expect data to contain 0x10, however, it contains 0x02.

对于 Enum.A 它包含 0x00 ,对于 Enum.B 它包含 0x01

For Enum.A it contains 0x00 and for Enum.B it contains 0x01.

在我看来,它存储值的索引而不是其实际原始数据。有人可以解释这种行为吗?

To me, it looks like it stores an index of the value instead of its actual raw data. Could someone explain this behavior?

P.S。如果我使用 rawValue ,则效果很好。但是,我想了解背后的原因,因为这个原因,所以我无法创建将值转换为NSData的通用函数。

P.S. If I use rawValue it works perfectly. However, I want to understand the reason behind, since because of it I cannot create a generic function to convert values to NSData.

推荐答案

Swift ABI仍在开发中(预计将在Swift 4中修复)。枚举在内存中的表示方式

The Swift ABI is still work in progress (expected to be fixed with Swift 4). The way enums are represented in memory is described here.

您的案例是 c-like枚举 ,因为它有...

Your case is a "c-like enum" because is has...


  • 两个或更多案例

  • 没有相关值

引用ABI文档:


枚举被布置为整数标签,其位数最少,可以容纳所有情况。 [...]案件按声明顺序分配了标签值。

the enum is laid out as an integer tag with the minimal number of bits to contain all of the cases. [...] The cases are assigned tag values in declaration order.

此处的关键信息是最小位数 。这意味着(对于您的情况)实例应适合两位(因为您有三种情况)。 rawValue 0x10 将需要五个位,这将与ABI冲突。

The crucial information here is the "minimal number of bits". This means that (for your case) instances should fit into two bits (as you have three cases). The rawValue 0x10 would need five bits—which would be in conflict with the ABI.

编译器可能使用静态表在 Enum 实例和它们的 rawValue (并返回)实例之间进行转换。

The compiler probably uses static tables to convert between instances of Enum and their rawValue (and back).

下面是一个突出显示ABI特征的示例:

Here's an example that highlights this characteristic of the ABI:

enum Enum: UInt32
{
    case A = 0
    case B = 0xffffffff    // value that does not fit into one byte
}

assert(sizeof(Enum.self) == 1)

这篇关于Swift枚举字节表示是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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