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

后端 未结 1 1241
梦毁少年i
梦毁少年i 2021-01-27 10:06

I forked this project, so I am not as familiar with all of the details: https://github.com/nebs/hello-bluetooth/blob/master/HelloBluetooth/NSData%2BInt8.swift.

This is

相关标签:
1条回答
  • 2021-01-27 10:52

    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])
        }
    }
    
    0 讨论(0)
提交回复
热议问题