Swift 范围超出数据长度

Swift range exceeds data length

我有一个 python 服务器,我使用流委托写入和读取。它工作正常,但是当我开始匹配并且服务器发回数据时它崩溃了。

这是它崩溃的地方:

func checkForMessages() {
    while true {
        if inputBuffer.length < 4 {
            print("buffer length\(inputBuffer.length)")
            print( MemoryLayout.size(ofValue: Int()))
            print("application quit here")
            return
        }
        var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
        msgLength = UInt32(bigEndian: msgLength)
        print(inputBuffer.length)
        print(msgLength)
        if inputBuffer.length < msgLength {
            print("its returning here!")
            return
        }

        // ******Crashes on the line Below******

        let message: Data? = inputBuffer.subdata(with: NSRange(location: 4, length: Int(msgLength)))
        processMessage(message!)
        let amtRemaining: Int = inputBuffer.length - Int(msgLength) - 4
        if amtRemaining == 0 {
            inputBuffer = NSMutableData()
        }
        else {
            print("Creating input buffer of length \(amtRemaining)")
            inputBuffer = NSMutableData(bytes: inputBuffer.bytes + 4 + Int(msgLength), length: amtRemaining)
        }
    }
}

设置"let message"时崩溃。

我已经尝试了一些事情,比如试图弄乱范围本身,但我不太确定为什么它在做什么,我可以 post 用于发送消息的服务器代码如果需要,请返回。

因此,通过替换以下部分代码解决了问题:

 if inputBuffer.length < msgLength {
        return
    }

 if inputBuffer.length < msgLength + 4 {
        return
    }