【问题标题】:Type () does not conform to protocoltype() 不符合协议
【发布时间】:2015-12-02 08:45:50
【问题描述】:

我不知道原因,但我无法检查 UIImage 是否为 nil 即代码

        var arrayBuildingImage: [UIImage] = []

        for(var i = 0; i <= 100; i++){

            var path:String = self.getDocumentsDirectory().stringByAppendingPathComponent("building/\(i).png")

            if ( arrayBuildingImage[i] = UIImage(contentsOfFile: path)? ) {//ERROR HERE

            }
            else{
                break
            }

        }

错误:

Type () 不符合协议'BooleanType'

我正在使用 Swift 1.1

【问题讨论】:

  • 为什么使用 Swift 1.1 而不是 Swift 2?
  • 你确定你的arrayBuildingImage[i] = UIImage(contentsOfFile: path)?没有错字吗?你的意思不是arrayBuildingImage[i] == UIImage(contentsOfFile: path)? 对吧?

标签: ios swift


【解决方案1】:

你应该检查它是否为零:

let img : UIImage? = UIImage(contentsOfFile: path)
if img != nil {}

或使用“if let”语句:

if let img = UIImage(contentsOfFile: path) {}

并以更“迅速”的方式:

guard let img = UIImage(contentsOfFile: path) else { return }
// Do you stuff here

【讨论】:

    【解决方案2】:

    试试这个:

            arrayBuildingImage[i] = UIImage(contentsOfFile: path)?
            if ( arrayBuildingImage[i] != nil ) {//ERROR HERE
    
            }
            else{
                break
            }
    

    【讨论】:

      【解决方案3】:

      您正在使用 Swift。

      在 Swift 中,“if”语句的操作数必须是布尔表达式。赋值运算符不产生任何值(或 Void 类型的值,如果您愿意的话)。

      要么将赋值结果与 nil 进行比较,要么更好地使用“if let”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-28
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多