我有 pascal 和 C 背景,最近开始学习 Swift。 我遇到了超出常识的错误。
以下代码运行良好。
ForEach(0..<12) { word in
Text(String(word))
}
但是一旦 ForEach 从 .. 发生变化< to ... it gives an error of Cannot convert value of type 'ClosedRange' to expected argument type 'Range'
ForEach(0...12) { word in
Text(String(word))
}
这背后的机制/原因是什么? 对于陈旧的编码背景,很难理解其中的原因。 感谢您的帮助。
根据您的示例,有两种类型的范围。
let half = 0..<5
//Range<Int>
let closed = 0...5
//ClosedRange<Int>
并且 SwiftUI 中的
ForEach
将 Range
作为参数,所以这就是你收到错误的原因。您可以在下面的文档中看到。
public init(_ data: Range, @TableRowBuilder content: @escaping (Int) -> Content) 其中 Data == Range, ID == Int, V == Content.TableRowValue