- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是一个可以按预期工作的简单SwiftUI列表:
struct App: View {
let items = Array(100...200)
var body: some View {
List {
ForEach(items, id: \.self) { index, item in
Text("Item \(item)")
}
}.frame(width: 200, height: 200)
}
}
但是当我尝试通过将
items
替换为
items.enumerated()
来枚举项目时,出现以下错误:
Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that '(offset: Int, element: Int)' conform to 'Hashable'
Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'EnumeratedSequence<[Int]>' conform to 'RandomAccessCollection'
最佳答案
TL; DR
警告:如果您习惯于将enumerated()
与ForEach
一起使用,则有一天您可能会遇到EXC_BAD_INSTRUCTION
或Fatal error: Index out of bounds
异常。这是因为并非所有集合都具有从0开始的索引。
更好的默认设置是使用zip
代替:
ForEach(Array(zip(items.indices, items)), id: \.0) { index, item in
// index and item are both safe to use here
}
(如果您的商品符合
id: \.1
,则也可以使用
Identifiable
。)
enumerated()
with ForEach
in production since not all collections are zero-index based上的人们:
This is technically not the most correct way to do this. It would be more correct, and more verbose, to zip the
todos
array with its indices collection. In this case we are safe because we are dealing with a simple 0-based index array, but if we were doing this in production we should probablyzip
-based approach.
/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
/// consecutive integer starting at zero and *x* represents an element of
/// the sequence.
///
/// This example enumerates the characters of the string "Swift" and prints
/// each character along with its place in the string.
///
/// for (n, c) in "Swift".enumerated() {
/// print("\(n): '\(c)'")
/// }
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"
///
/// When you enumerate a collection, the integer part of each pair is a counter
/// for the enumeration, but is not necessarily the index of the paired value.
/// These counters can be used as indices only in instances of zero-based,
/// integer-indexed collections, such as `Array` and `ContiguousArray`. For
/// other collections the counters may be out of range or of the wrong type
/// to use as an index. To iterate over the elements of a collection with its
/// indices, use the `zip(_:_:)` function.
///
/// This example iterates over the indices and elements of a set, building a
/// list consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Now that the `shorterIndices` array holds the indices of the shorter
/// names in the `names` set, you can use those indices to access elements in
/// the set.
///
/// for i in shorterIndices {
/// print(names[i])
/// }
/// // Prints "Sofia"
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
///
/// - Complexity: O(1)
在特定情况下,由于您使用的是基于0的索引数组,因此
enumerated()
可以很好地使用,但是由于上面的详细信息,始终依赖
enumerated()
可能会导致非显而易见的错误。
ForEach(Array(items.enumerated()), id: \.offset) { offset, item in
Button(item, action: { store.didTapItem(at: offset) })
}
// ...
class Store {
var items: ArraySlice<String>
func didTapItem(at index: Int) {
print(items[index])
}
}
首先要注意的是,我们用
Button(item...
躲过了一个项目符号,因为
enumerated()
保证了
item
可以直接访问而不会引起异常。但是,如果我们使用
item
代替
items[offset]
,则很容易引发异常。
print(items[index])
行很容易导致异常。
zip
方法。
zip
的另一个原因是,如果您尝试将相同的代码用于不同的Collection(例如Set),则在索引到类型(
items[index]
)时可能会遇到以下语法错误:
Cannot convert value of type 'Int' to expected argument type 'Set.Index'
zip
的方法,您仍然可以索引到集合中。
import PlaygroundSupport
import SwiftUI
// MARK: - Array
let array = ["a", "b", "c"]
Array(array.enumerated()) // [(offset 0, element "a"), (offset 1, element "b"), (offset 2, element "c")]
Array(zip(array.indices, array)) // [(.0 0, .1 "a"), (.0 1, .1 "b"), (.0 2, .1 "c")]
let arrayView = Group {
ForEach(Array(array.enumerated()), id: \.offset) { offset, element in
PrintView("offset: \(offset), element: \(element)")
Text("value: \(array[offset])")
}
// offset: 0, element: a
// offset: 1, element: b
// offset: 2, element: c
ForEach(Array(zip(array.indices, array)), id: \.0) { index, element in
PrintView("index: \(index), element: \(element)")
Text("value: \(array[index])")
}
// index: 0, element: a
// index: 1, element: b
// index: 2, element: c
}
// MARK: - Array Slice
let arraySlice = array[1...2] // ["b", "c"]
Array(arraySlice.enumerated()) // [(offset 0, element "b"), (offset 1, element "c")]
Array(zip(arraySlice.indices, arraySlice)) // [(.0 1, .1 "b"), (.0 2, .1 "c")]
// arraySlice[0] // ❌ EXC_BAD_INSTRUCTION
arraySlice[1] // "b"
arraySlice[2] // "c"
let arraySliceView = Group {
ForEach(Array(arraySlice.enumerated()), id: \.offset) { offset, element in
PrintView("offset: \(offset), element: \(element)")
// Text("value: \(arraySlice[offset])") ❌ Fatal error: Index out of bounds
}
// offset: 0, element: b
// offset: 1, element: c
ForEach(Array(zip(arraySlice.indices, arraySlice)), id: \.0) { index, element in
PrintView("index: \(index), element: \(element)")
Text("value: \(arraySlice[index])")
}
// index: 1, element: b
// index: 2, element: c
}
// MARK: - Set
let set: Set = ["a", "b", "c"]
Array(set.enumerated()) // [(offset 0, element "b"), (offset 1, element "c"), (offset 2, element "a")]
Array(zip(set.indices, set)) // [({…}, .1 "a"), ({…}, .1 "b"), ({…}, .1 "c")]
let setView = Group {
ForEach(Array(set.enumerated()), id: \.offset) { offset, element in
PrintView("offset: \(offset), element: \(element)")
// Text("value: \(set[offset])") // ❌ Syntax error: Cannot convert value of type 'Int' to expected argument type 'Set<String>.Index'
}
// offset: 0, element: a
// offset: 1, element: b
// offset: 2, element: c
ForEach(Array(zip(set.indices, set)), id: \.0) { index, element in
PrintView("index: \(index), element: \(element)")
Text("value: \(set[index])")
}
// index: Index(_variant: Swift.Set<Swift.String>.Index._Variant.native(Swift._HashTable.Index(bucket: Swift._HashTable.Bucket(offset: 0), age: -481854246))), element: a
// index: Index(_variant: Swift.Set<Swift.String>.Index._Variant.native(Swift._HashTable.Index(bucket: Swift._HashTable.Bucket(offset: 2), age: -481854246))), element: b
// index: Index(_variant: Swift.Set<Swift.String>.Index._Variant.native(Swift._HashTable.Index(bucket: Swift._HashTable.Bucket(offset: 3), age: -481854246))), element: c
}
// MARK: -
struct PrintView: View {
init(_ string: String) {
print(string)
self.string = string
}
var string: String
var body: some View {
Text(string)
}
}
let allViews = Group {
arrayView
arraySliceView
setView
}
PlaygroundPage.current.setLiveView(allViews)
关于swift - 在SwiftUI中,如何在ForEach中使用.enumerated()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59295206/
有没有办法获取/获取 SwiftUI 中 Text 对象中使用的当前字体?前任。 Text("abc").font() 不起作用。 最佳答案 可以从环境访问当前字体: struct ChildView
我想知道为什么 SwiftUI 中的 2 个元素之间会出现这种间距?以及如何控制/修改它?我尝试向 ExtractedView 添加一些填充,但没有任何改变。似乎它是由 .frame(height:
目标 获取要显示在scrollView中的数据 预期结果 实际结果 另类 使用List,但不灵活(无法删除分隔符,不能具有多列) 码 struct Object: Identifiable {
我想使用 onIncrement 和 onDecrement 在手动(非绑定(bind))模式下使用 Stepper View 。当我尝试实现下限和上限时,有一种奇怪的行为,例如。年龄值不低于 1 或
我正在尝试在 SwiftUI 中显示全局警报。无论当前显示/呈现在屏幕上的内容(例如工作表),此警报都应显示在所有内容的顶部。 这是我的代码: @main struct MyApp: App {
我正在尝试为我的模态表实现一个关闭按钮,如下所示: struct TestView: View { @Environment(\.isPresented) var present va
我有一个在 SwiftUI 中处理的主细节应用程序,但是一旦在第一个 DetailView 上,NavBar 中的 NavigationLink 就不再有效。我把它写成一个简单的演示: struct
这是我想做的一个最小的、可重复的例子。 我有一系列的段落。 var notes = [ "One line paragraph", "This is a small paragraph
有什么方法可以使用 SwiftUI 找到父 View 大小,我查看了文档和示例,似乎大多数(如果不是全部)都是硬编码大小,理想情况下我想找到父 View 的大小然后设置基于父级大小百分比的 subvi
我有一个 列表由单元格组成,每个单元格包含一个图像和一列文本,我希望以特定的方式布局。左侧图像,占宽度的四分之一。文本的剩余空间,左对齐。 这是我得到的代码: struct TestCell: Vie
这是 iOS 13 Health 应用程序的屏幕截图 - 用户个人资料。我最近开始使用 swiftui并想知道如何开发如下所示的屏幕。我尝试了简单和分组的列表样式。但我无法看到下面的布局。 这样的UI
更新 : 14 个月后,AppKit 发行说明中有这样一个有趣的说明: A TextField that you are editing inside a selected List row now
我来自 React,在那里我使用 useMemo 来确保某些计算不会过于频繁地执行。我如何在 SwiftUI 中做类似的事情? 考虑这个例子: struct MyView: View { va
我已经查看并尝试了所有不同的组合,但我无法弄清楚如何更改 View 导航栏标题的文本颜色。这是我的代码,我也在尝试使用我已经从我的 Assets 文件夹中添加和使用的自定义颜色。我知道这个问题已被问过
如何更改swiftUI上导航栏“返回”按钮的文本? form from a navigationLink init(){ UINavigationBar.appearance().backgr
具有渐变填充的矩形并尝试为颜色变化设置动画。 ... Rectangle() .fill(LinearGradient( gradient: .init(stops:
我已经将UITextView包装在UIViewRepresentable中,并包括了Coordinator作为UITextViewDelegate,但是未调用事件。我究竟做错了什么? struct T
我需要更改 swiftUI 中 tabItem 徽章的颜色。我创建了这个 Pod https://github.com/jogendra/BadgeHub可以与 swiftUI 一起使用吗? 我有选项
我可以使用以下代码在 UIKIt 中定义常量字体: let appFont = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)
通常我可以在 SwiftUI 中显示这样的项目列表: enum Fruit { case apple case orange case banana } struct Frui
我是一名优秀的程序员,十分优秀!