繁体   English   中英

SwiftUI 字符串符合 Identifiable 似乎不正确

[英]SwiftUI String conform Identifiable seems not correct

我在List使用一个数组,在List有一个ForEach ,例如:

struct AView: View {

    @State var foo: [String] = ["a", "b", "c"]

    var body: some View {
        ZStack {
            Color.white
            List {
                ForEach(foo.indices) { index in
                    Text(foo[index])
                }
            }
        }

    }
}

这很好用,然后我想添加一个按钮来插入新项目:

   List {
            ForEach(foo.indices) { index in
                Text(foo[index])
            }
        }
        Button("Add") {
            foo.append("foo")
        }
    }

然后我得到了错误,这显然是:

ForEach<Range<Int>, Int, Text> count (4) != its initial count (3). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

这里提到

Identifiable或使用ForEach(_:id:content:)

我可以使用ForEach(foo.indices, id:\\.self)来解决这个问题。

我也想尝试Identifiable ,不要在ForEachForEach(foo.indices)使用id:\\.self

我为 String 添加了扩展名,例如:

extension String: Identifiable {
    public var id: String { self }
}

但还是遇到了同样的问题。 有什么我想念的吗? 谢谢!

编辑

根据评论@New Dev,因为我是字面indices ,所以我添加了对Int扩展:

extension Int: Identifiable {
    public var id: Int { self }
}

仍然不起作用。

ForEach有多个init重载。

init(Range<Int>, content: (Int) -> Content)仅适用于恒定范围 - 因此出现错误。

init(Data, content: (Data.Element) -> Content)要求Data符合可Identifiable元素的RandomAccessCollection 这就是你想要使用的。

问题是您的RandomAccessCollectionRange<Int>符合的)是Int元素的集合。

尽管您可以使Int符合Identifiable ,但这仍然不起作用。 它仍然会使用带有Range<Int>参数的第一个ForEach.init ,因为方法重载偏好——即Range<Int>匹配更具体的initRange<Int>参数,而不是匹配不太具体的initRandomAccessCollection


所以,你的选择是:

  1. 通过显式指定id使用第三个init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)
ForEach(foo.indices, id:\.self) { index in 
}
  1. 转换为Array<Int>并符合Int: Identifiable
extension Int: Identifiable { var id: Self { self } }

ForEach(Array(foo.indices)) { index in 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM