'How to convert for-in loop into foreach in Swift?
I have one for loop where I found index in repeating hence I want to convert into foreach loop.
for (key, _) in details {
let product = product
details[key]?.title = product.first?.name ?? ""
details[key]?.amount = Double(product.first?.prices ?? 0.0)
}
I tried this as below but still here details[key]? is repeating
details.forEach { key, value in
let product = product
details[key]?.title = cartProduct.first?.name ?? ""
details[key]?.amount = Double(product.first?.prices ?? 0.0)
}
May I know, how to convert this into foreach in Swift so that I don't need to write [key] every-time.
Solution 1:[1]
You can do it this way:
details.forEach { _, value in
value value = value // Add this if your `value` is a struct
let product = product
value.title = cartProduct.first?.name ?? ""
value.amount = Double(product.first?.prices ?? 0.0)
}
Solution 2:[2]
details.forEach {
var mutableProduct = $0
let product = product
mutableProduct.value.title = cartProduct.first?.name ?? ""
mutableProduct.value.amount = Double(product.first?.prices ?? 0.0)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gus Eulalio |
| Solution 2 | Muzahid |
