"Variable 'xxx' was never mutated; consider changing to 'let' constant" 错误

"Variable 'xxx' was never mutated; consider changing to 'let' constant" ERROR

我有以下问题。我在下面使用这段代码,但遇到了问题

"Variable 'characteristic' was never mutated; consider changing to 'let' constant"

for var characteristic:CBCharacteristic in service.characteristics ?? [] {
    print(str)
    _selectedPeripheral!.writeValue(str.dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse)
}

当我更改为 "let" 时,出现错误:

'let' pattern cannot appear nested in an already immutable context

为什么它向我推荐更改,然后将其标记为错误?

您只需删除 var,使您的代码:

for characteristic in service.characteristics ?? [] {
    print(str)
    _selectedPeripheral!.writeValue(str.dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse)
}

因为 characteristic 默认是不可变的。