gpt4 book ai didi

Swift 导入字典到 tableviewcell

转载 作者:行者123 更新时间:2023-11-28 07:01:34 25 4
gpt4 key购买 nike

我正在尝试创建一个 TableView 来显示名为 tableText<String, String> 的字典的内容.但是在cellForRowAtInSection方法,当我做类似的事情时

let obj = tableText[indexPath.row]

它给我一个错误说

cannot subscript a value of type 'Dictionary<String, String> with an index of Int. 

我也尝试过类似的东西

let obj = tableText[indexPath.row] as? NSDictionary

但是错误依然存在。

你能帮我解决这个问题吗?

最佳答案

如果您只需要这些值,您可以从字典中获取一个值数组,并在该数组上使用 indexPath.row。

if let text = tableText.values[indexPath.row] as? String {
cell.textLabel.text = text
}

显然,如果您需要对它们进行排序,您必须对它们进行排序,因为字典不是基于键排序的。

如果你想让它们按字母顺序排序,你可以这样做

let sortedText = tableText.values.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

并使用这个 sortedText 数组作为你的数据源

关于Swift 导入字典到 tableviewcell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com