Boon
Boon

Reputation: 41500

Swift nil is not the same as Objective-C nil

Apple documentation mentions that:

Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types

When is the above knowledge useful? Will compiler convert Swift nil to Objective-C nil and vice versa automatically where applicable?

Upvotes: 2

Views: 4295

Answers (2)

drewag
drewag

Reputation: 94733

Yes, the compiler will convert Objective-C nils to Swift nils. That is why when translating from Objective-C all pointers must become optionals in Swift.

The usefulness of this knowledge is right in the description you gave:

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

In Swift all types can be made optional and therefore nil. For example, in Objective-C you cannot make an NSInteger nil.

Technically nil is just a case in the Optional enum:

enum Optional<T> {
    case None
    case Some(T)
}

nil is just shorthand for the None case

Upvotes: 8

Kevin
Kevin

Reputation: 56089

First, that means that only optionals can have a nil value, e.g.:

// Objc:
Object *foo = nil;
foo = [Object new];
foo = nil;

// Swift
var foo: Object = nil // not allowed
var bar: Object = Object()
bar = nil // not allowed

var foo: Object? = nil // fine
foo = Object()
foo = nil

But the more important application is in primitive types. If you have an int in objc, and it might have an invalid value, you need to decide on that invalid value and make sure both caller and callee know it.

// Objc
int i = 0; // Is this valid? 
i = -1 // What about this?

// Swift
var bar: int? = nil // Invalid.
bar = 0  // valid.
bar = -1 // valid.

Upvotes: 2

Related Questions