如何解决使用解析服务器在 Swift 中迭代 For In 循环
我有一个充满用户的聊天,当然还有一个用户名数组。我想为用户名数组中的每个用户获取与用户名关联的个人资料图片。但是,解析只能按我所知道的升序/降序排序。
因此,我需要弄清楚如何对收到的数据进行排序。 我最终会附加一个 url 用作图片。
W
解决方法
我不知道解析服务器,所以我真的不知道是否存在以特定顺序获取响应的规定,如果存在则应该是最佳解决方案。但是您的解决方案存在一个通用问题,即时间复杂度。 您有两个嵌套的 for 循环,这使得它的最坏情况复杂度为 O(n^2),我想您至少可以将其复杂度降低到 >O(n)
func getPics(_ completionHandler: @escaping () -> Void) {
let query = PFQuery(className: "_User")
var dictionary: [String : Int] = [:]
var unit = 0
for username in usernameArray {
unit += 1
dictionary[username] = unit
}
query.findObjectsInBackground(block: { (objects: [PFObject]?,error: Error?) in
if let objects = objects,error == nil {
let objectsDict = Dictionary(grouping: objects,by: { $0["username"] as! String /* typically you should be accessing $0.username,but again am not aware of PFObject */})
for user in self.usernameArray {
if let pfuser = objectsDict[user]?[safe: 0] as? PFObject {
let imageFile = pfuser["profilePic"] as? PFFileObject
let imageFileString = imageFile?.url as! String
if let url = URL(string: imageFileString) {
let replacedImageUrlString = imageFileString.replacingOccurrences(of: "[removed for privacy]",with: "removed for privacy")
let url = replacedImageUrlString as NSString
self.urlArray.append(url)
}
}
}
completionHandler()
}
})
}
一旦你得到PFObject
的数组,你就可以创建一个以用户名为键,PFObject为值的字典,一旦你有了字典,你就可以在PFObject >O(1),因此您可以运行单个 for 循环,从而将代码的复杂性降低到 O(n)
P.S如果您想知道 [safe: 0]
是什么,您可以添加这个方便的扩展来安全地访问数组中特定索引处的对象
链接:Safe (bounds-checked) array lookup in Swift,through optional bindings?
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
P.P.S:我的回答完全忽略了 Dictionary(grouping:
API 本身的复杂性,我试图寻找信息,但找不到。但我认为它的 O(n) 不太确定,不管它是什么,如果它不是 O(n^2) 你仍然会受益
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。