1

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

Guntis Treulands
  • 4,764
  • 2
  • 50
  • 72
Suresh Kumar Durairaj
  • 2,104
  • 16
  • 24

1 Answers1

0

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • You're justifying that swift does something that already exist in objective-C particularly in the case of object-returns-null-when-non-exist situation, not something new/beyond than objective-C. Is that the primary intention of having optional variable/constant in Swift, Swift must do something more than that with optional variable/constant possibly? If you knew more, please share it. – Suresh Kumar Durairaj Jun 12 '14 at 05:53
  • 1
    @Suresh The "optional by default" behavior of Objective-C is a C legacy, and it is not particularly good. There are simply no "required" objects - all objects are "optional". Swift offers "required" objects, and makes them the default, because this is the behavior that you want most often. It also adds "optional" for less frequent situations when you want the "optional object" behavior. – Sergey Kalinichenko Jun 12 '14 at 09:42
  • Thank you very much for sharing your insightful idea on this topic. Thank you again :-) – Suresh Kumar Durairaj Jun 12 '14 at 10:04