swiftoptional-variables

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


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....


Solution

  • 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.