Swift 如何使用节访问UITableView中的数据模型[String:[String]]?
我正在准备我的数据模型,以便它可以在UITableView中使用Swift 如何使用节访问UITableView中的数据模型[String:[String]]?,swift,uitableview,ios9,sections,Swift,Uitableview,Ios9,Sections,我正在准备我的数据模型,以便它可以在UITableView中使用 var folderHolder: [String: [String]]? folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]] 如何通过索引(根据UITableView的需要)访问此词典中的键和对象 我在操场上试过这个,结果卡住了。谢谢你在这方面的帮助 // Need numb
var folderHolder: [String: [String]]?
folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]
如何通过索引(根据UITableView的需要)访问此词典中的键和对象
我在操场上试过这个,结果卡住了。谢谢你在这方面的帮助
// Need number of Keys
// Expected result: 2
folderHolder!.count
// Need number of elements in Key
// Expected: All and Recent are in Projects, so 2 would be expected
folderHolder!["Projects"]
folderHolder!["Projects"]!.count
// How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
folderHolder![1]!.count
// Need specific element
// Input parameter: Key index, Value index
// Expected: "Folder 2"
folderHolder![1]![1]
// I don't know why it only works when I state the key explicitly.
folderHolder!["Smart Folders"]![1]
按照字典的设置方式,不能像索引数组那样对字典进行索引。由于字典的Key:Value性质,顺序并不重要,因此像这样订阅:
folderHolder[1]
将不起作用。这样的索引只能在数组中工作,因为数组中的顺序很重要,因此需要维护
Swift文件规定:
字典在没有定义顺序的集合中存储相同类型的键和相同类型的值之间的关联。每个值都与唯一键相关联,该键在字典中充当该值的标识符。与数组中的项不同,字典中的项没有指定的顺序。
经过进一步研究,找到了解决方案: 字典键需要转换为数组。可以通过索引(UITableView的部分)访问数组项,并返回键的名称。键的名称可用于访问字典的值(UITableView的行) 以下是正确的游乐场数据作为参考:
var folderHolder: [String: [String]]?
folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]
let folderHolderArray = Array(folderHolder!.keys)
// Need number of Keys
// Expected: 2
folderHolder!.count
folderHolderArray.count
// Need number of elements in Key
// Expected: All and Recent are in Projects, so 2 would be expected
folderHolder!["Projects"]
folderHolder!["Projects"]!.count
// How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
folderHolderArray[1]
// Need specific element
// Input parameter: Key index, Value index
// Expected: "Folder 2"
//folderHolder![1]![1]
let folderHolderSection = folderHolderArray[1]
let folders = folderHolder![folderHolderSection]
let folder = folderHolder![folderHolderSection]![1]
非常感谢。看来这本字典不是合适的类型。在进一步研究之后,有一种方法可以将字典键转换为数组。然后可以通过索引(按特定顺序)对数组进行寻址。