5

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?

3
  • 2
    Don't use filter(), it doesn't make sense. Use map() instead: numberWords = numberWords.map({ return $0 == "two" ? "2" : $0 }) Commented Mar 27, 2018 at 9:15
  • as @Larme mentioned, you should map the array not filter it. The purpose of using filter is to determine (validate) which element should be exist in the collection, which could lead to decrease the number of element in a collection; map is just a transformation of the element, which probably what are you aiming to in your case... Commented Mar 27, 2018 at 9:27
  • Does this answer your question? Find an item and change value in custom object array - Swift Commented Jun 26, 2020 at 21:28

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it's Totally fine. How can we change score.activeDate . in self.monthlyActiveDayzModel.data?.responseMap?.resultsList?.scores = self.monthlyActiveDayzModel.data?.responseMap?.resultsList?.scores?.map { score in score.activeDate = "newValue" } where monthlyActiveDayzModel is struct model.
5

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

2 Comments

Fab!!. How can we change score.activeDate . in self.monthlyActiveDayzModel.data?.responseMap?.resultsList?.scores = self.monthlyActiveDayzModel.data?.responseMap?.resultsList?.scores?.map { score in score.activeDate = "newValue" } where monthlyActiveDayzModel is struct model.
@Ramesh That's a different question. I'd ask a new SO question about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.