我想删除数组的前n个字节,但如果使用dropFirst或removeFirst,会出现构建错误
最终,我希望cumulative_receive_bytes中的所有字节都位于第一个\n之后。
var cumulative_receive_bytes = Array<UInt8>(repeating: 0, count: 1024)
. . .
var latest_hub_bytes = Array<UInt8>(repeating: 0, count: 1024)
. . .
cumulative_receive_bytes += latest_hub_bytes
let hub_string = String(bytes: cumulative_receive_bytes, encoding: .ascii)
let hub_lines = hub_string!.split( whereSeparator: .isNewline)
let message_from_hub = hub_lines[ 0 ]
cumulative_receive_bytes = cumulative_receive_bytes.removeFirst( message_from_hub.count + 1 )
... ERROR IS: Cannot assign value of type '()' to type '[UInt8]' <<<<<<<<<<<<<<<<<<
cumulative_receive_bytes = cumulative_receive_bytes.dropFirst( message_from_hub.count + 1 )
... ERROR IS: Cannot assign value of type 'Array<UInt8>.SubSequence' (aka 'ArraySlice<UInt8>') to type '[UInt8]' <<<<<<<<<<<
removeFirst
是一个变异函数,它直接变异数组。它不返回修改后的数组。这就是为什么会出现无法将函数(类型为()
(分配给数组的错误。
你可以说
cumulative_receive_bytes.removeFirst( message_from_hub.count + 1 )
在第二种情况下,dropFirst
返回一个ArraySlice
-您需要使用它来创建一个新的数组
cumulative_receive_bytes = Array(cumulative_receive_bytes.dropFirst( message_from_hub.count + 1 ))
关于风格的注意事项,在Swift中,变量应该使用camelCase,而不是_-cumulativeReceiveBytes
而不是cumulative_receive_bytes