Home > OS >  SwiftUI: checking if next index exists in a ForEach
SwiftUI: checking if next index exists in a ForEach

Time:11-28

I am iterating through a ForEach and some arrays have 1 index and I want to leave those as-is. For arrays with multiple indices, I want to separate the values by a pipe so at the end of each loop, I want to see if the a greater index exists by doing $0 1 but I keep getting: Cannot convert value of type 'String' to expected condition type 'Bool' and `Cannot convert value of type 'String' to expected condition type 'Int'

ForEach(item.currency, id: \.self) {
    Text(verbatim: $0)
        .font(Font.custom("Avenir", size: 18))
        .foregroundColor(Color("47B188"))
        .padding(.leading, 18)
                
    if (item.currency[$0   1]) {
        Text("|")
    }
}

CodePudding user response:

You need to iterate your collection indices and check if the index 1 is less then the collection endIndex:

ForEach(item.currency.indices) {
    Text(verbatim: item.currency[$0])
        .font(Font.custom("Avenir", size: 18))
        .foregroundColor(Color("47B188"))
        .padding(.leading, 18)
    if $0   1 < item.currency.endIndex {
        Text("|")
    }
}
  • Related