我对
Swift语法相当新,并且我的代码“无法通过下标分配:下标仅获取”,我收到此错误
这是从行:friendDictionary [(friendUID as?String)!] = [“name”:friendsData![“name”]]
任何关于正确方法的建议都会非常有帮助.
func getFriendsUIDs() {
if FBSDKAccesstoken.currentAccesstoken() == nil {
print("Failed to start graph request")
return
}else{
}
if FBSDKAccesstoken.currentAccesstoken() != nil {
}
let parameters = ["fields": "name,id,picture"]
FBSDKGraphRequest(graPHPath: "/me/friends",parameters: parameters).startWithCompletionHandler {
(NSURLConnection,result,requestError) in
let friendIds = result["id"] as? NSDictionary
let friendsData = friendIds!["data"] as? [NSDictionary]
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("friendUIDs").observeEventType(.Value,withBlock: { (snapshot) in
self.FriendUIDs = NSArray()
self.FriendUIDs = (snapshot.value as? NSArray)!
print(self.FriendUIDs)
var friendDictionary = NSDictionary()
for friendUID in self.FriendUIDs {
friendDictionary[(friendUID as? String)!] = ["name": friendsData!["name"]]
}
self.fetchFriendFeed(friendDictionary)
}) { (error) in
print(error.localizedDescription)
}
}
}
func fetchFriendFeed(friendDictionary: NSDictionary) {
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
for friendUID in FriendUIDs {
ref.child("users").child(friendUID as! String).child("Agenda").observeEventType(.ChildAdded,withBlock: { (snapshot) in
print(snapshot)
if let dictionary = snapshot.value as? [String: AnyObject] {
let friendPost = FriendPost()
friendPost.picture = friendDictionary[friendUID as! String]? ["picture"] as? String
friendPost.activity = dictionary["activity"] as? String
friendPost.date = dictionary["date"] as? String
friendPost.time = dictionary["time"] as? String
friendPost.friendname = friendDictionary[friendUID as! String]? ["name"] as? String
self.friendPosts.append(friendPost)
dispatch_async(dispatch_get_main_queue(),{
self.collectionView?.reloadData()
解决方法
与Swift无关.您已经选择使用Objective-C,实际上是将friendDictionary设为NSDictionary. NSDictionary是不可变的;你不能分配或以任何方式改变它.这只是关于Objective-C的一个事实. Swift var声明对这个事实没有任何影响.
一个更好的选择,因为你在Swift中编写,将使用Swift字典,它是[AnyHashable:Any]()(在Swift 3中).当你与Objective-C交谈时,这将与NSDictionary交换,但它会给你一个可变字典,因为你(正确地)用var声明了它.