ForEach Character in String

Viewed 1269

In SwiftUI, how do you loop through each character in a string using ForEach?

For example

let some_string = "A⍺甲あ"

VStack {
  ForEach(....) {....
    Text(String(character_in_the_string))
  }
}

Output

A
⍺
甲
あ
2 Answers

ForEach requires that the value passed to it conforms to RandomAccessCollection. A String is a Sequence, and it can be turned into a RandomAccessCollection by making it into an Array.

Use Array() to turn the string into [Character]:

VStack {
    ForEach(Array(some_string), id: \.self) { character in
        Text(String(character))
    }
}

In general, you should be careful to choose an id that is unique. Since some_string could contain repeated characters, you could instead use .enumerated() to turn each Character into an (offset, element) pair (where offset is its position in the String). Then use .offset as the id and .element to retrieve the Character from the tuple pair:

VStack {
    ForEach(Array(some_string.enumerated()), id: \.offset) { character in
        Text(String(character.element))
    }
}

This would matter, for instance, if you were animating the removal of characters from the string. If you use the character as the .id, SwiftUI may choose the wrong character to animate if several of the same character are listed in a row.

let yourString = Array("A⍺甲あ") // convert your string to an array

VStack {
    ForEach(0..<yourString.count) { num in
        Text(String(yourString[num]))
    }
}

Output:

A 
⍺ 
甲 
あ
Related