swift - 属性 setter 中的 NilLiteralConvertible

标签 swift properties

很快我就有了这个:

 ///3.5.1.8 Range is ± 32,576 FPM, FPM of 32640 means max.  Also can be invalid (nil)
var vVelcotiy: Int? {
    get {

        let ret : Int16 = decode12Bit2sCompliment(bytes[15], bytes[16], useEntireFirstByte: false)

        return Int(ret * 64);
    }
    set {

        if (bytes[15] == 8 && bytes[16] == 0) {
            return nil
        }

        if let n = newValue {
            let nv = n / 64
            bytes[15] = (bytes[15] & 0xF0) | (UInt8(nv) >> 8)
            bytes[16] = UInt8(nv)

        } else {
            bytes[15] = (bytes[15] & 0xF0) | 0xF8
            bytes[16] = 0x00
        }
    }
}

我收到类型“()”不符合协议(protocol)“NilLiteralConvertible”的错误,但我已将我的属性声明为可选,所以我很困惑。

我希望能够做到:

var a : vVelocity = nil

最佳答案

阅读 rintaro 的回答并考虑到我的评论,我认为您在 setter 中放错了第一个检查,看起来它应该属于 getter 中:

var vVelcotiy: Int? {
    get {
        if (bytes[15] == 8 && bytes[16] == 0) {
            return nil
        }

        let ret : Int16 = decode12Bit2sCompliment(bytes[15], bytes[16], useEntireFirstByte: false)

        return Int(ret * 64);
    }
    set {

        if let n = newValue {
            let nv = n / 64
            bytes[15] = (bytes[15] & 0xF0) | (UInt8(nv) >> 8)
            bytes[16] = UInt8(nv)

        } else {
            bytes[15] = (bytes[15] & 0xF0) | 0xF8
            bytes[16] = 0x00
        }
    }
}

现在您的 getter 有可能返回 nil,并且您的 setter 不依赖于现有值。

关于swift - 属性 setter 中的 NilLiteralConvertible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28487328/

相关文章:

ios - 使用 Core Data(在 SwiftUI 中)提供的数据并与另一个 View 共享

JavaScript 虚拟宠物

java - 如何对读取属性文件的类进行单元测试

c# - "Getters should not include large amounts of logic."是真是假?

ios - 如何在使用变换(缩放、旋转和平移)时合并 UIImages?

swift - 如何在我的搜索 Controller 中使用 queryStartingAtValue 来搜索用户?

swift - Swift 中的日期/时间自然语言近似

ios - 在 fscalendar 中禁用过去的日子

java - 从逗号分隔属性列表创建数组的更优雅的解决方案?

javascript - 如何在 JavaScript 对象文字中使用变量作为键?