Skip to content

Instantly share code, notes, and snippets.

@alenm
Created February 23, 2021 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alenm/26a353cee3a8f17e85d548b09ccdbe75 to your computer and use it in GitHub Desktop.
Save alenm/26a353cee3a8f17e85d548b09ccdbe75 to your computer and use it in GitHub Desktop.
ForEach and with an index using SwiftUI
// 01 Example with struct
// Use ForEach to provide views based on a `RandomAccessCollection` of some data type.
// see documentation: https://developer.apple.com/documentation/swiftui/foreach
// I want the index you can do the following...
// You use `results.enumerated().map({$0}` which takes your results and returns it into an array
// I have seen examples where you could do it like `Array(results.enumerated())`
// NOTE:
// The collection’s elements must conform to Identifiable or you need to provide an id parameter to the ForEach initializer.
// In this example I'm using a struct.
struct Foo: Indentifiable {
var id: UUID = UUID()
var name: String
}
let results = [Foo(name: "Example 1"), Foo(name: "Example 2")]
ForEach(results.enumerated().map({$0}), id:\.0) { index, item in
// ... you can pass in the index or item
}
// Example with Strings
ForEach(["baseball", "basketball", "hockey"].enumerated().map({$0}), id:\.0) { index, item in
Text("\(item)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment