【问题标题】:how to give nil parameter in if condition in swift?如何在swift中的if条件中给出nil参数?
【发布时间】:2015-07-14 12:22:31
【问题描述】:

在 Objective-C 中:

if (!myImageView) {
    NSLog(@"hdhd");
}
else {
 //DO SOMETHING
}

但在 Swift 中:

if (!myImageView) {  
   println("somethin")
}
else {
   println("somethin")
}

这段代码给了我错误:

找不到“!”的重载接受提供的参数'

myImageView 是类变量UIImageView

我该怎么办?

【问题讨论】:

    标签: swift if-statement


    【解决方案1】:

    通常,在 Swift 中检查 nil 变量的最佳方法是使用 if letif var 语法。

    if let imageView = self.imageView {
        // self.imageView is not nil
        // we can access it through imageView
    } else {
        // self.imageView is nil
    }
    

    但要使其正常工作(或与 nil== nil!= nil 进行比较),self.imageView 必须是可选的(隐式解包或其他方式)。

    非可选项不能nil,因此编译器不会让您将它们与nil 进行比较。他们永远不会是nil

    所以如果if let imageView = self.imageViewself.imageView != nilself.imageView == nil 给你错误,那几乎可以肯定是因为self.imageView 不是可选的。

    【讨论】:

      【解决方案2】:

      如果您的变量是UIImageView 类型,那么它永远不能为零。 但是,如果您希望您的代码等同于您的 Objective-C 代码,请将变量类型更改为 UIImageView?(可选类型)并替换:

      if (!myImageView) {
      

      与:

      if (myImageView == nil) {
      

      【讨论】:

      【解决方案3】:

      测试myImageView != nilmyImageView.image != nil

      【讨论】:

      • myImageView != nil 用 '!=' 代替 '!' 给出相同的错误但 myImageView.image != nil 没有给出错误。但我不想在图像上设置条件
      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2021-08-31
      相关资源
      最近更新 更多