[英]How do you use Set with Table View?
I want to iterate through Set
and display them in a table, but I'm getting an error that says:我想遍历
Set
并将它们显示在一个表中,但我收到一条错误消息:
Fatal error: Invalid index
致命错误:无效索引
Following is my code:以下是我的代码:
@NSManaged public var progress: Set<Progress>
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return progress.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = progress[progress.index(progress.startIndex, offsetBy: indexPath.row)].comment
return cell
}
A Set
is unordered.一个
Set
是无序的。 Sort
the set – for example by date
– to get an array in a specific order and use this as data source array对集合进行
Sort
(例如按date
)以按特定顺序获取数组并将其用作数据源数组
var progresses = [Progress]()
...
progresses = progress.sorted{$0.date < $1.date}
Simply use indexPath.row
as index in the Array
after converting the Set<Progress>
to Array<Progress>
using the Array(Set)
initializer.使用
Array(Set)
初始化程序将Set<Progress>
转换为Array<Progress>
后,只需使用indexPath.row
作为Array
中的索引。
cell.textLabel?.text = Array(progress)[indexPath.row].comment
Better Approach: Using the Array(Set)
initializer in cellForRowAt
each time is less efficient, also the order of elements cannot be guaranteed.更好的方法:每次在
cellForRowAt
中使用Array(Set)
初始化程序效率较低,也无法保证元素的顺序。 It would be better to do it just once right after the progress: Set<Progress>
is initialized.最好在
progress: Set<Progress>
已初始化。
var progressArray: [Progress] // set this right after `progress` is set
Then in cellForRowAt
:然后在
cellForRowAt
:
cell.textLabel?.text = progressArray[indexPath.row].comment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.