Swift 将字典导入 tableviewcell
Swift import dictionary to tableviewcell
我正在尝试创建一个 table 视图来显示名为 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 { [=11=].localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }
并使用这个 sortedText 数组作为您的数据源
我正在尝试创建一个 table 视图来显示名为 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 { [=11=].localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }
并使用这个 sortedText 数组作为您的数据源