在if语句中使用多个包含函数(Swift)

时间:2015-03-21 12:55:55

标签: ios arrays swift parse-platform

有没有办法在if语句中使用多个“contains(array,value)”函数?我有一个查询存储在数组的结果中。如果结果为零,我执行一组操作。但是,如果数组不是nil,我想查看某些对象是否出现在其中:

var user: PFUser?

    override func viewDidLoad() {
        super.viewDidLoad()

        //get the two players
        if let user = user{

            var userQuery = PFQuery(className: "Game")
            userQuery.whereKey("user1", equalTo: user)
            userQuery.whereKey("isActive", equalTo: true)

            var userQuery2 = PFQuery(className: "Game")
            userQuery2.whereKey("user2", equalTo: user)
            userQuery2.whereKey("isActive", equalTo: true)

            var currentUserQuery = PFQuery(className: "Game")
            currentUserQuery.whereKey("user1", equalTo: PFUser.currentUser())
            currentUserQuery.whereKey("isActive", equalTo: true)

            var currentUserQuery2 = PFQuery(className: "Game")
            currentUserQuery2.whereKey("user2", equalTo: PFUser.currentUser())
            currentUserQuery2.whereKey("isActive", equalTo: true)

            var query = PFQuery.orQueryWithSubqueries([userQuery, userQuery2, currentUserQuery, currentUserQuery2])
            query.findObjectsInBackgroundWithBlock{
            (results: [AnyObject]!, error: NSError!) -> Void in

                if error == nil{

                    //if there are no active games, start new game
                    if results == nil{

                        //start game code


                    } else if contains(results, user) as [AnyObject]! && contains(results, PFUser.currentUser()) as [AnyObject]! {

                        println(results)
                    }

                    }
                }

            }
        }

使用&&运算符在行上返回错误:Cannot invoke '&&' with an argument of type '([AnyObject]!,[AnyObject]!)'。关于我如何测试以查看是否在数组中找到用户和PFUser.current_user()对象的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

问题是你试图将包含 func调用的结果(Bool)转换为AnyObjects的数组。

您需要做的只是比较包含(结果,用户)和包含(结果,PFUser.currentUser())函数调用的结果。但它不会编译。

为了让您的编译器满意,您需要将结果数组转换为 [PFUser]

的数组

参见代码:

if let users = results as? [PFUser] {
    if contains(users, user) && contains(users, PFUser.currentUser())  {
       println(users)
    } 
}