Home > Software engineering >  How to use the same name to define the new struct while keeping the original functions in Swift?
How to use the same name to define the new struct while keeping the original functions in Swift?

Time:07-19

I'm trying to define a new struct to extend the function of SwiftUI's ForEach, which introduced index to it. It can be used like below

ForEach(array) { index, item in
}

I attached my code below. But after I define this struct. the original syntax (ForEach(array) { item in }) doesn't work. I know I can simply replace index with _ to avoid error, but it's impossible to modify hundreds of this in old code. So how can I fix this? Or any alternative to this?

struct ForEach<Data: RandomAccessCollection,Content: View>: View where Data.Element: Identifiable, Data.Element: Hashable {
    let data: Data
    @ViewBuilder let content: (Data.Index, Data.Element) -> Content
    
    init(_ data: Data, content: @escaping (Data.Index, Data.Element) -> Content) {
        self.data = data
        self.content = content
    }
    
    var body: some View {
        SwiftUI.ForEach(Array(zip(data.indices, data)), id: \.1) { index, element in
            content(index, element)
        }
    }
}

CodePudding user response:

Do not use this. It will confuse people because nothing is mentioning what the id is.

This is what you were looking for:

https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md

ForEach(collection.indexed(), id: \.index) {
  $0.index
  $0.element
  • Related