Reputation: 177
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?
Upvotes: 5
Views: 10712
Reputation: 86651
Just as a bit of variety, you could write an in place map, which would probably be more efficient for large arrays (see also reduce(into:)).
extension Array
{
mutating func mapInPlace(transform: (inout Element) -> Void)
{
for i in 0 ..< self.count
{
transform(&self[i])
}
}
}
var a = ["one", "two", "three"]
a.mapInPlace{ if $0 == "two" { $0 = "2" } }
Upvotes: 5
Reputation: 26036
Do not use filter()
, it doesn't make sense.
The point of filter is to iterate each elements and tells if you keep it (return true) or not (return false) according to your desires.
Instead, use map()
:
numberWords = numberWords.map({ return $0 == "one" ? "1" : $0 })
I used a ternary if and explicitly write a "return" (which is not necessary since it's already done "internally" (you need to returns something)), but you can do it more explicitly keeping your previous code:
numberWords = numberWords.map({
if $0 == "one" {
return "1"
}
return $0 })
map()
is more suited for that. You use it if you want to iterate each items and modify it if needed which is what you want to do.
Upvotes: 14