ylliX - Online Advertising Network

Tip: How to find and replace a value inside array of arrays?

Imagine you have a structure like:

[[String, String], [String, String], [String, String],]

and you need to replace a second value. How to do that?

So for more reality, let’s create and array like:

var items: [[String]] = [
["entry 1", "value 1"],
["entry 2", "value 2"],
["entry 3", "value 3"]
]

At this point replacing “value 2” is quite easy:

if let idx = items.firstIndex(where: { $0.first == "entry 2" }) {
    items[idx][1] = "new value 2"
}

If you want to play with this, check out SwiftFiddle, or try below (just push play button):

Leave a Reply