What is the intended use of optional variable/constant in swift

笑着哭i 提交于 2020-01-03 02:55:15

问题


In objC,

NSString *stringValue = @"123s";
NSInteger *intValue = [stringValue integerValue];   
NSLog(@"intergerValue %@",intValue);

if(!intValue)
{
   NSLog(@"caught null object");

}
else
{
    // Do appropriate operation with the not null object
}

prints " interValue (null) " " caught null object "

and the binding is done safely by using !(not) operator inside if condition...

But whereas, in swift the equivalent snippet using optional variable is

 var normalValue : String = "123s"
 var optionalValue = normalValue.toInt()
 println("optionvalue \(optionalValue)")

  if optionalValue {
     // Do appropriate operation with the not nil value
  }
  else{

      println("caught null object")
  }

this "optional binding" is done in objectiveC also, then what is the exact use of having optional variable/constant. And it's also been said that we can avoid returning null object instead we can return nil value. What is the problem when we return a null object, does it cause performance issues? Your valid thoughts....


回答1:


The intention behind optional types was to let programmers make variables that might not have a value. It was the default model in Objective-C, it has been reversed in Swift, because the language requires variables to have a value by default.

Objective-C refers to all objects through pointers (hence the asterisk * after the type name). Since all pointers are allowed to have no value (i.e. nil) one could think of all Objective-C objects as optional, i.e. the corresponding variable may have no value at all.

Since Swift does not have a requirement of C compatibility on the source code level, language designers choose to require objects to have a value of the specified type, and provided support for making variables that may not have a value through optional types.



来源:https://stackoverflow.com/questions/24163716/what-is-the-intended-use-of-optional-variable-constant-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!