Why does Swift's map function behave differently with an array of boolean values?

Viewed 40
import SwiftUI

var arrayInt = [1, 2, 3, 4, 5]
var resultInt1 = arrayInt.map {$0}
var resultInt2 = arrayInt.map {$0 + 3}
print(resultInt1)
print(resultInt2)

var arrayString = ["a", "b", "C", "d", "e"]
var resultString1 = arrayString.map {$0}
var resultString2 = arrayString.map {$0.uppercased()}
print(resultString1)
print(resultString2)

Error: Cannot use mutating member on immutable value: '$0' is immutable

var arrayBool = [true, true, true, true, true]
var resultBool1 = arrayBool.map {$0}
var resultBool2 = arrayBool.map {$0.toggle()} 
print(resultBool1)
print(resultBool2)
1 Answers

The $0 element inside a map is considered immutable let

toggle Docs

 mutating func toggle()

Mutates the instance itself , so it gives error as $0 is a let

uppercased Docs

func uppercased() -> String

Returns a string after processing the $0 , so it passes as it doesn't mutate $0

Related