Cannot pass immutable value as inout argument: function call returns immutable value

微笑、不失礼 提交于 2019-12-02 12:01:13

The original code was incorrect. UInt8(value) generates a new, immutable value which you cannot write to. I assume the old compiler just let you get away with it, but it was never correct.

What they meant to do was to write to the expected type, and then convert the type at the end.

extension Data {
    func int8Value() -> Int8 {
        var value: UInt8 = 0
        copyBytes(to: &value, count: MemoryLayout<UInt8>.size)

        return Int8(value)
    }
}

That said, I wouldn't do it that way today. Data will coerce its values to whatever type you want automatically, so this way is safer and simpler and very general:

extension Data {
    func int8ValueOfFirstByte() -> Int8 {
        return withUnsafeBytes{ return $0.pointee }
    }
}

Or this way, which is specific to ints (and even simpler):

extension Data {
    func int8Value() -> Int8 {
        return Int8(bitPattern: self[0])
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!