Iterating Over Data with ForEach in SwiftUI
Iterating over an array of items is very common when coding. In this article, let's look at how we can iterate over an array in a View, as well as iterate over an array in a function.
Use ForEach to loop through an array in a View and in a function
Let's say we have an array of authors.
var authors = ["Pranzo", "Deepu", "Selena", "John"]
..
Iterating in a View
To iterate over the authors array and display it in a View, we just need to use the ForEach structure:
var body: some View {
VStack {
ForEach(authors) {author in
Text(author)
}
}
..
Iterate in a function
You can use the forEach method to loop through an array in a function:
func iterateOverAuthors(authors: Array[String]) -> String? {
authors.forEach { author in
return author
}
return nil
}
..
Another method is to use the for...in method:
func iterateOverAuthors(authors: [String]) -> String? {
for author in authors {
return author
}
return nil
}
..
When using the for...in method, we can also include the index by simply adding it right after the for. Don't forget to add .enumerated() right after the array, which will take into consideration the index of each item in the array.
func iterateOverAuthors(authors: [String]) -> String? {
for (index, author) in authors.enumerated() {
return "\(index + 1) - \(author)"
}
return nil
}
..
Comments
Post a Comment