34

I have the following problem. I use this code below and I get the issue

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

When I change to "let", there's an Error:

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

Why does it recommend me the change and afterwards mark it as an error?

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
Luke Pistrol
  • 1,199
  • 3
  • 12
  • 26

1 Answers1

64

You just need to remove var, making your code:

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

because characteristic is immutable by default.

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78