Reputation: 905
I have one tuple array for
e.g. [(Student, Bool)]
and other Bool
array as [true, false, false]
I want to update tuple bool value as per bool array, for example:
var tupleArray = [("first", true), ("second", false ), ("third", true)]
var boolArray = [true, false, false]
Result should be:
var tupleArray = [("first", true), ("second", false ), ("third", false)]
Is there any best way to achieve this?
Upvotes: 1
Views: 408
Reputation: 51972
A simple solution is to enumerate and use map
tupleArray = tupleArray.enumerated().map { ($1.0, boolArray[$0]) }
Or use zip
as mentioned in the comments
tupleArray = Array(zip(tupleArray.map { $0.0 }, boolArray))
If the arrays are of different size or rather if tupleArray
is longer than boolArray
we have an issue, the first code will crash and the second will only include the same number of elements from tupleArray
as exists in boolArray
To fix the first code we could use the original value from tupleArray
tupleArray = tupleArray.enumerated()
.map { ($1.0, $0 < boolArray.count ? boolArray[$0] : $1.1) }
Upvotes: 2
Reputation: 757
You can use the next trick for that:
var tupleArray = [("first", true), ("second", false ), ("third", true)]
print(tupleArray)
var boolArray = [true, false, false]
for i in 0...(tupleArray.count - 1) {
tupleArray[i].1 = boolArray[i]
}
print(tupleArray)
Result will be next:
[("first", true), ("second", false), ("third", true)]
[("first", true), ("second", false), ("third", false)]
Upvotes: -3