Created
February 23, 2021 15:57
-
-
Save alenm/26a353cee3a8f17e85d548b09ccdbe75 to your computer and use it in GitHub Desktop.
ForEach and with an index using SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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