✨ForEach examples
Loop over a range of integers
// init(
// _ data: Range<Int>,
// content: @escaping (Int) -> Content
// )
// ---------------------------------------
// ForEach<Range<Int>, Int, Text>
// Data = Range<Int>
// ID = Int
// Content = Text
struct ContentView: View {
let positions = ["First", "Second", "Third"]
var body: some View {
ForEach(0..<positions.count) { index in
Text(positions[index])
}
}
}Loop over any data
Loop over an array of strings and specified \.self key path, which refers to the string itself as an identifier.
// init(
// _ data: Data,
// id : KeyPath<Data.Element, ID>,
// content: @escaping (Data.Element) -> Content
// )
// ------------------------------------------------
// ForEach<[String], String, Text>
// Data = [String]
// ID = String
// Content = Text
struct ContentView: View {
let coworkers = [
"Gabriel Lang", "John Brunelle", "Matthew Arieta", "Wayne Ohmer",
"Ralph Dugue", "Alex Burnett", "Craig Heneveld", "Bill Munsell"
]
var body: some View {
VStack {
ForEach(coworkers, id: \.self) { name in
Text(name)
}
}
}
}Loop over Identifiable data
The last one is the most compact form of all three, but it required each element in a collection to conform Identifiable protocol.
上面例子中的自訂型別稍微改一下,就可以使用這個 initializer。
examples for ForEach.
Last updated
Was this helpful?