尝试使用Swift模拟C联合会出现运行时异常

尝试使用Swift模拟C联合会出现运行时异常,swift,Swift,在C中: 在Swift中(使用带有关联值的枚举): 但这不会导致运行时异常: let regA = Register.b(255, 0) print(regA.l) print(regA.h) let regB = Register.w(UInt16(256)) print(regB.w) 我无法找出问题所在,因为似乎很难在枚举定义中跟踪该问题。我看到两个问题 对于问题1,您正在从UInt16创建一个UInt8,如果不限制该值,该值将溢出。您可以使用UInt8(截断位模式:w)或UInt8(w

在C中:

在Swift中(使用带有关联值的枚举):

但这不会导致运行时异常:

let regA = Register.b(255, 0)
print(regA.l)
print(regA.h)
let regB = Register.w(UInt16(256))
print(regB.w)
我无法找出问题所在,因为似乎很难在枚举定义中跟踪该问题。

我看到两个问题

对于问题1,您正在从
UInt16
创建一个
UInt8
,如果不限制该值,该值将溢出。您可以使用
UInt8(截断位模式:w)
UInt8(w&0xff)

对于第二期,
UInt16(l |(h>8)中的
l
h
} } 变量w:UInt16{ 开关(自){
案例b(let l,let h):返回UInt16(l)| UInt16(h)我不会为此定义枚举。如果值是从两个字节或一个单词创建的,为什么会有区别呢?我会定义一个结构,或者一个具有计算属性的
lowByte
highByte
,与中类似的
扩展UInt16
。我接受了@vacawama的答案,因为它修复了我的pro问题就在海湾,但我一定会采用你的解决方案,当我重构我的代码。谢谢。
enum Register {
    case b(UInt8, UInt8)
    case w(UInt16)

    var l: UInt8 {
        switch(self) {
        case .b(let l, _): return l
        case .w(let w): return UInt8(w)
        }
    }

    var h: UInt8 {
        switch(self) {
        case .b(_, let h): return h
        case .w(let w): return UInt8(w >> 8)
        }
    }

    var w: UInt16 {
        switch(self) {
        case .b(let l, let h): return UInt16(l | (h << 8))
        case .w(let w): return w
        }
    }
}
let regA = Register.b(255, 0)
print(regA.l)
print(regA.h)
let regB = Register.w(UInt16(256))
print(regB.w)
print(regA.w)
print(regB.l)
print(regB.h)
enum Register {
    case b(UInt8, UInt8)
    case w(UInt16)

    var l: UInt8 {
        switch(self) {
        case .b(let l, _): return l
        case .w(let w): return UInt8(w & 0xff)  // issue 1
        }
    }

    var h: UInt8 {
        switch(self) {
        case .b(_, let h): return h
        case .w(let w): return UInt8(w >> 8)
        }
    }

    var w: UInt16 {
        switch(self) {
        case .b(let l, let h): return UInt16(l) | UInt16(h) << 8  // issue 2
        case .w(let w): return w
        }
    }
}