Initializer

init(_:id:content:)

Creates an instance that uniquely identifies and creates views across updates based on the provided key path to the underlying data’s identifier.

Declaration

init(_ data: Data, id: KeyPath<Data.Element, ID>, content: @escaping (Data.Element) -> Content)
Available when Content conforms to View.

Parameters

data

The data that the ForEach instance uses to create views dynamically.

id

The key path to the provided data’s identifier.

content

The view builder that creates views dynamically.

Discussion

It’s important that the id of a data element doesn’t change, unless SwiftUI considers the data element to have been replaced with a new data element that has a new identity. If the `id` of a data element changes, then the content view generated from that data element will lose any current state and animations.

See Also

Creating a Collection of Views

init(Data, content: (Data.Element) -> Content)

Creates an instance that uniquely identifies and creates views across updates based on the identity of the underlying data.

init(Range<Int>, content: (Int) -> Content)

Creates an instance that computes views on demand over a given constant range.