Complete the code to create a list showing numbers from 1 to 5 using ForEach.
List {
ForEach(1...5, id: \.[1]) { number in
Text("Number \(number)")
}
}The id: \.self\ tells SwiftUI to use each number itself as a unique identifier.
Complete the code to display a list of fruit names using ForEach.
let fruits = ["Apple", "Banana", "Cherry"] List { ForEach(fruits, id: \.[1]) { fruit in Text(fruit) } }
For arrays of strings, id: \.self\ uses each string as a unique identifier.
Fix the error in the ForEach loop by completing the id parameter correctly.
struct ContentView: View {
let names = ["Anna", "Bob", "Cara"]
var body: some View {
List {
ForEach(names, id: \.[1]) { name in
Text(name)
}
}
}
}id or index which are not valid here.Using id: \.self\ tells SwiftUI to use each string as its own unique id.
Fill both blanks to create a list of numbers squared using ForEach.
List {
ForEach(1...3, id: \.[1]) { num in
Text("Square: \(num [2] num)")
}
}id: \.self\ uses the number itself as id, and * multiplies the number by itself to get the square.
Fill all three blanks to create a list showing names in uppercase using ForEach.
let names = ["alice", "bob", "carol"] List { ForEach(names, id: \.[1]) { name in Text(name.[2]().[3]()) } }
lowercased() instead of uppercased().id: \.self\ uses each string as id, uppercased() converts to uppercase, and the last () calls the method properly.