NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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!!

   

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

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

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until October 1st.

Click to save your free spot now

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.