Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios NSData:在展开可选值时意外发现nil_Ios_Swift - Fatal编程技术网

Ios NSData:在展开可选值时意外发现nil

Ios NSData:在展开可选值时意外发现nil,ios,swift,Ios,Swift,这可能是基本的swift问题,但我对swift或iOS开发还不熟悉。我收到错误致命错误:在展开可选值时意外发现nil 对于下面的函数 func Call() -> NSData? { let nilObj: NSData? = nil if(false){ // Doing something } e

这可能是基本的swift问题,但我对swift或iOS开发还不熟悉。我收到错误
致命错误:在展开可选值时意外发现nil

对于下面的函数

    func Call() -> NSData?
        {        
            let nilObj: NSData? = nil 
            if(false){  
                  // Doing something     
              }
            else
              {         
                 return nilObj!        
              } 
        }

我只想在else条件下返回nil NSData,但我得到了错误。我确信我遗漏了一些明显的东西,任何人都可以帮忙。

您声明
nilObj
为可选项,并用
nil
初始化它。然后在你的
else
子句中,你试图打开它。要解决此问题,只需删除该

将代码更改为:

func Call() -> NSData?
{        
     let nilObj: NSData? = nil 
     if(false)
     {  
        // Doing something     
     }
     else
     {         
         return nilObj       
     } 
}

嗯,错误说明了一切!您正在尝试强制展开可选的。在展开可选项时,应使用
if let
语法。

swift中的可选项一开始可能会令人困惑,但请记住它们只是一个枚举,类似于:

enum Optional<T> {
   case None
   case Some(T)  // swift enums can have data associated to them
}
使用swift的一种更惯用的方法是通过可选绑定

// binds the constant 'value' to your optional if it is non-nil
if let value = optional {
    value.someMethod()
} else {
    // optional is nil
}
第三种检查方法是使用保护语句。不过,guard语句的语义与以前的语句略有不同。您还可以混合使用保护语句和可选绑定

在swift中,Guard语句是一个简洁的功能,因为你可以专注于你想要的条件,而不是你不想要的条件。它还将处理违反的需求的代码放在相应需求的旁边。与使用if语句做同样的事情相比,警卫通过明确意图来提高可读性


要了解更多信息,请查看。

的“基本”部分,只需返回nil即可。用小写的第一个字母命名方法是Swift的惯例
// binds the constant 'value' to your optional if it is non-nil
if let value = optional {
    value.someMethod()
} else {
    // optional is nil
}
guard optional != nil else {
    // optional is nil.
    // by the end of this branch you must exit the block that
    // encloses the guard statement, such as with a return or break
    return
}
// if control reaches here you're guaranteed optional is non-nil