[英]IOS Swift reading data from a dictionary of [String: [AnotherKindOfDictionary] ] ( )
我想从包含图像字典(或实际上是任何对象)的字典中读取数据。 每个字典都有一个键(字符串)。
对于某种视觉上的理解,这就是我想要实现的目标:
userIdOne-> [image1,image2,image3,image4]
userIdTwo-> [image1,image2,image3]
userIdThree-> [image1,image2,image3,image4,image5]
userIdFour-> [image1,image2]
注意:尽管具有相同的“标题”,这些图像也不是同一幅图像。 他们只是属于每个用户。 userId是[String:...。图像字典是我在此问题的标题中提到的[AnotherKindOfDictionary]。 我想要每个单元格中的每个userId及其图像。 因此,总共将显示4个单元,但在点击时会按顺序显示其图像。
问题是我想将此数据放在UITableView或UICollectionView中。 我曾经与这两家公司合作过,所以无论哪种都行。 类似于手套的工作原理。 每当点击一个单元格时,就会依次显示该用户的图像。
我已经能够将每个用户ID作为键将数据加载到字典中,但是我在collectionView中使用数据时遇到了麻烦(我目前的选择,尽管我可以使用tableView)
这是我的代码:
var stories = [String : [StoryMedia]]()
// StoryMedia is a struct containing info
struct StoryMedia {
var storyMediaId: String?
var creatorId: String?
var datePosted: String?
var imageUrl: String?
init(storyMediaKey: String, dict: Dictionary<String, AnyObject>) {
storyMediaId = storyMediaKey
creatorId = dict["creatorId"] as? String
datePosted = dict["dateposted"] as? String
imageUrl = dict["imageUrl"] as? String
}
}
... Now in the actual viewController class UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let storyCell: StoryCell!
storyCell = collectionView.dequeueReusableCell(withReuseIdentifier: storyReuseIdentifier, for: indexPath) as! StoryCell
// What should I do here?
return storyCell
}
问题在于尝试设置每个单元。 我无法通过其键提取每个字典值并将其用于每个单元格。
我试过使用:
// Failed attempt 1)
let story = stories[indexPath.row]
// but I get an ambiguous reference to member 'subscript' error
// Failed attempt 2)
for story in stories {
let creatorId = story.key
let sequenceOfStoryItems = story.value
for singleStoryItem in sequenceOfStoryItems {
// do something...
}
}
// but looping through an array for a collection view cell
// does nothing to display the data and if I were to guess,
// would be detrimental to memory if
// I had a lot of "friends" or users in my "timeline"
字典没有顺序,因此将它用于cellForItem函数很尴尬(以及为什么不能使用该下标)。 您也许可以使用字典的值(即忽略键),但这可能与b / n运行不同。 我的意思是,您可以在stories.values数组上使用下标(不记得对“ values”的确切调用,但是它很接近... allValues?...不确定,没有办法请立即仔细检查),而不是故事词典。
var stories = [String : [StoryMedia]]()
是否需要作为字典? 字典没有顺序,因此无法像您要求的那样对它们进行索引。 你能把它做成一个元组数组吗? var stories = [(username:String, media:StoryMedia)]()
然后,您可以将计划存储在原始键中的任何值添加到元组的username:
字段中。 如果您更喜欢元组,则可以制作另一个具有username
和media
属性的结构。
通过一个简单的stories.filter{}
调用将单个username
或media
结构从数组中拉出应该是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.