写这个多条件If-Statement的正确方法是什么?

时间:2015-06-02 01:49:47

标签: ios swift if-statement parse-platform

正确处理这两个条件if-statement的正确方法是什么?

我收到的编译错误是could not find an overload for '==' that accepts the supplied arguments

如果我只使用其中一种,那就没关系,但是当我添加第二种时它不起作用。

    for item in imageOutlets {

        if collectionObjects.count > 0 {

            let imageObject = self.collectionObjects.objectAtIndex(count) as! PFObject
            let imageFile = imageObject.objectForKey(smallThumbImage) as! PFFile
            imageFile.getDataInBackgroundWithBlock({ (data, error) -> Void in

                if (error == nil) || (imageFile != nil) {

                    item.image = UIImage(data: data!)

                } else {

                    item.image = UIImage(named: "placeholder")
                    println("error loading image")
                }

2 个答案:

答案 0 :(得分:1)

只有Optional变量可以为nil,因此请将代码更改为

 let imageFile = imageObject.objectForKey(smallThumbImage) as? PFFile
 imageFile?.getDataInBackgroundWithBlock({(data: NSData!, error: NSError!) -> Void in
           if (error == nil){ //here do not need to check imageFile
               item.image = UIImage(data: data!)
           } else {
               item.image = UIImage(named: "placeholder")
               println("error loading image")
            }
})

答案 1 :(得分:0)

正如Leo所说,只有选项可以是nil,并且你明确地使用as!运算符将imageFile强制转换为非可选项:

let imageFile = imageObject.objectForKey(smallThumbImage) as! PFFile

您可以使用as?运算符使imageFile可选,您的比较应该有效。更好的是:将as?if-let结构一起使用:

if let imageObject = self.collectionObjects.objectAtIndex(count) as? PFObject, let imageFile = imageObject.objectForKey(smallThumbImage) as? PFFile {
    //imageObject and imageFile are guaranteed to be properly cast and non-nil in this scope.
}

这也更安全,因为如果您的对象无法转换为PFFile,则使用as!将导致运行时错误。