想要从解析中查询一个有时可能为空的数组,但xcode不会让我

时间:2015-11-06 11:07:46

标签: xcode swift parse-platform forced-unwrapping

func reloadFriendList() {
    var query = PFQuery(className:"userFriendClass")
    query.whereKey("username", equalTo:user!.username!)
    query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            for object in objects! {
                self.friendList = object["friends"] as! [String]
                print(self.friendList)
                self.reloadTableView()
            }
        } else {

            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }

    }
}

我想保存对象[“friends”],这是一个从用户名解析到

的数组
var friendList = [String]()

但我收到错误:“致命错误:在展开Optional值时意外发现nil”, 当数组为空时,意味着用户没有任何朋友,但当用户至少有一个或多个朋友时,它可以正常工作。

2 个答案:

答案 0 :(得分:1)

你需要准备好你的代码来处理nil个案和案例,其中" objects"是一个空数组。

如果这是我的代码,我会做类似的事情:

for object in objects {
    if let friendList = object["friends"]
    {
         self.friendList = friendList
    } else {
         // make sure that your class's `friendList` var is declared as an optional
         self.friendList = [String]()
    }
}

答案 1 :(得分:1)

由于objects是可选的,可能是nil,因此您需要安全地打开它。一种方法是使用 nil coalescing operator 来展开它,或者在objectsnil时替换空数组。您可以再次使用它来安全地打开朋友列表:

for object in objects ?? [] {
    self.friendList = (object["friends"] as? [String]) ?? []

您还可以使用可选绑定 if let来安全地展开内容:

if let unwrappedObjects = objects {
    for object in unwrappedObjects {
        if let friends = object["friends"] as? [String] {
            self.friendsList = friends
        } else {
            // no friends :-(
            self.friendsList = []
        }
    }
}