Pages

Monday, August 10, 2020

What is the difference between nil of Swift and nil of Objective-C?

 Swift's nil isn't the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object.

In Swift, nil is not a pointer, it's the absence of a value of a certain type. 

Optionals of any type can be set to nil, not just object types.


“The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” However, this only works for objects—it doesn’t work for structures, basic C types, or enumeration values. For these types, Objective-C methods typically return a special value (such as NSNotFound) to indicate the absence of a value. This approach assumes that the method’s caller knows there’s a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for any type at all, without the need for special constants.”


Excerpt From: Apple Inc. “The Swift Programming Language (Swift 5.2)”. Apple Books. https://books.apple.com/us/book/the-swift-programming-language-swift-5-2/id881256329

No comments: