我一直在尝试使用 plist 字典中的名字填充 TableView 。配置单元格值时出现错误。
我的代码:
// Created a function to get plist dictionary values
func getSwiftArrayFromPlist() -> (Array<Dictionary<String,String>>) {
let path = Bundle.main.path(forResource: "Sheet1", ofType: "plist")
var arr: NSArray?
arr = NSArray(contentsOfFile: path!)
return (arr as? Array<Dictionary<String,String>>)!
}
override func viewDidLoad() {
super.viewDidLoad()
//var mainGroup = [String]()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let array1 = getSwiftArrayFromPlist().count
return array1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
//var key = Array(self.array.keys)[indexPath.row]
var key = getSwiftArrayFromPlist()["firstname"]
var value = getSwiftArrayFromPlist()[key]
return cell
}
在 var 键处出现错误:
Cannot subscript a value of type 'Array>' with an index of type 'String'
我的目标是在 TableView 中获取名字列表(键是“名字”值是实际的名字。
最佳答案
getSwiftArrayFromPlist() 的返回类型是数组。但是您尝试使用键“firstname”像字典一样访问它
应该是:-
var key = getSwiftArrayFromPlist()[indexPath.row]["firstname"]
var value = getSwiftArrayFromPlist()[indexPath.row][key!]
关于swift - 如何使用字典为 TableView 分配单元格值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48897682/