How can we update element of an array
Method 1:-Working code:-
var numberWords = ["one", "two", "three"]
for i in 0..<numberWords.count {
if numberWords[i] == "two" {
numberWords[i] = "2"
}
}
But I am looking for solution using Swift high order function
Method 2:
numberWords = numberWords.filter {
if $0 == "one" {
$0 = "1"//cannot assign value $0 is immutable
}
return true
}
Error thrown : Cannot assign value $0 is immutable
Is it possible or Method 1 is only way?
filter(), it doesn't make sense. Usemap()instead:numberWords = numberWords.map({ return $0 == "two" ? "2" : $0 })mapthe array notfilterit. The purpose of usingfilteris to determine (validate) which element should be exist in the collection, which could lead to decrease the number of element in a collection;mapis just a transformation of the element, which probably what are you aiming to in your case...