UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: SwiftUI: ForEach iterating over an array of key-value pairs

Forums > SwiftUI

Hi all, I have a sorted dictionary as so:

let ingredients = extractIngredients().sorted(by: { $0.key < $1.key} )

extractIngredients() returns a [String : String], and ingredients should be a [(String, String)]. However, I want to display the key-value pairs with ForEach, but I'm not sure how I would go about that. This is my loop:

ForEach(ingredients) { pair in
    Text("**\(pair.key)**: \(pair.value)")
}

It gives me the following error: Cannot convert value of type '[Dictionary<String, String>.Element]' (aka 'Array<(key: String, value: String)>') to expected argument type 'Range<Int>'

Thanks for all the help!!

2      

Hi, It needs to have a key, value in and an id: \.key:

ForEach(ingredients, id: \.key) { key, value in
    Text("**\(key)**: \(value)")
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.