evanparial
evanparial

Reputation: 45

How do I use Text in SwiftUI to display an array of tuple values?

I have declared an array of tuples as such:

    var countryFlag: [(flag: String, description: String)] = [("πŸ‡ΊπŸ‡Έ", "United States"), ("πŸ‡°πŸ‡·", "South Korea"), ("πŸ‡΅πŸ‡­", "Phillipines"), ("πŸ‡¨πŸ‡¦", "Canada"), ("πŸ‡©πŸ‡ͺ", "Germany")]

I am trying to call and display these values in an HStack using Text(), but my error is:

use of unresolved identifier 'flag' and 'description'

here's my whole code :

import SwiftUI
import PlaygroundSupport


struct ContentView: View
{
    var countryFlag: [(flag: String, description: String)] = [("πŸ‡ΊπŸ‡Έ", "United States"), ("πŸ‡°πŸ‡·", "South Korea"), ("πŸ‡΅πŸ‡­", "Phillipines"), ("πŸ‡¨πŸ‡¦", "Canada"), ("πŸ‡©πŸ‡ͺ", "Germany")]
    
    var body: some View
    {
        List(0..<5)
        {
            item in
            HStack
                {
                    Text("\(flag)")
                    Text("\(description)")
                }
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

Upvotes: 0

Views: 1769

Answers (1)

vacawama
vacawama

Reputation: 154593

List(0..<5) { item in loops 5 times and item takes on the values of 0 though 4. Those are indices into your countryFlag array. Subscript countryFlag with item which will then give you a tuple. You can then access the values in that tuple with .flag and .description.

Replace:

Text("\(flag)")
Text("\(description)")

with:

Text("\(countryFlag[item].flag)")
Text("\(countryFlag[item].description)")

A better way to go about this would be to List your countryFlag array using \.flag as the id.

List(countryFlag, id: \.flag) { item in
    HStack {
        Text("\(item.flag)")
        Text("\(item.description)")
    }
}

Finally, if you use flag, description in in the closure to deconstruct the tuple into two variables, you can use the Text views as you defined them:

List(countryFlag, id: \.flag) { flag, description in
    HStack {
        Text("\(flag)")
        Text("\(description)")
    }
}

Upvotes: 1

Related Questions