无法将不可变值作为inout参数传递:函数调用返回不可变值 [英] Cannot pass immutable value as inout argument: function call returns immutable value

查看:113
本文介绍了无法将不可变值作为inout参数传递:函数调用返回不可变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我分叉了这个项目,所以我对所有细节都不熟悉: https://github.com/nebs/hello-bluetooth/blob/master/HelloBluetooth/NSData%2BInt8.swift .

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.

这是NSData扩展的全部部分,我正在使用该扩展将8位值发送到Arduino.

This is all part of an extension of NSData that the I am using to send 8-bit values to an Arduino.

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

    return value
}

但是,在Swift 3中看来,这现在在copyBytes部分引发了一个错误.尽管我看到了一些解决方案,例如在参数中传递地址,但我不想冒险破坏代码的其余部分.关于该怎么做有什么建议吗?

However, it appears in Swift 3 that this now throws an error in the copyBytes section. Although I have seen some solutions such as passing an address in the parameter, I did not want to risk breaking the remaining parts of the code. Any suggestions on what to do for this?

推荐答案

原始代码不正确. UInt8(value)生成一个新的,不可变的值,您无法写入该值.我认为旧的编译器只是让您摆脱它,但是那从来都不是正确的.

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

也就是说,我今天不会那样做. Data会自动将其值强制转换为您想要的任何类型,因此这种方式更安全,更简单且非常通用:

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

或者以这种方式,它特定于int(甚至更简单):

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

extension Data {
    func int8Value() -> Int8 {
        return Int8(bitPattern: self[0])
    }
}

这篇关于无法将不可变值作为inout参数传递:函数调用返回不可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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