Home > Software design >  How To Replace All Matching Array Elements?
How To Replace All Matching Array Elements?

Time:11-12

I am replacing an item in my array with this code:

var array = ["", "Orange", "Grape", "Apple"]
if let i = array.firstIndex(of: "") {
                            array[i] = "Blank"
                        }
                        print("\(array)"). //["Blank", "Orange", "Grape", "Apple"]

My only issue with this is it only replaces the FIRST item matching, so my question is-- is there any way to replace ALL items matching?

It's possible this has been answered before but I'm unable to find it.

CodePudding user response:

You can iterate your array with a map and replace empty strings with data.

array = array.map{$0.isEmpty ? "Blank" : $0}
  • Related