hbull
hbull

Reputation: 41

How nil can call functions in Objective-C and Swift

nil is similar but different concept in Objective-C and Swift.

In Objective-C

nil presents absense of Objective-C Object. in details, id is pointer of any objects. nil is id that indicates nothing.

So, any primitive types can not be nils

for example.

NSString *a = nil (o)
int a = nil (x)

In Swift

nil presents absense of any data types which is called Optional. so nil is kind of typealias of Optional?

Both languages, any nil types object can call a function.

For example.

NSString *name = nil;
[a lowercaseString];

let name: String? = nil
name.lowercased()

both cases do not occur null point exceptions.

How can presenting nothing and absense of any types can call a function?

Upvotes: 4

Views: 1606

Answers (1)

JeremyP
JeremyP

Reputation: 86661

nil is kind of typealias of Optional?

No. nil is syntactic sugar for Optional<T>.none where T is the type wrapped by the optional.

name: String? = nil 
name.lowercased()

No this is illegal. If you try it in playground, autocomplete will insert a question mark

name?.lowercased()
//  ^ here

which basically means if name is not nil, unwrap it and call lowercased() otherwise return nil.

nil in Objective-C and nil in Swift are fundamentally different "under the hood". nil in Objective-C is merely a null pointer. This is why primitives in Objective-C cannot be nil: they are not pointer types.

If you try to send a message to nil in Objective-C, it sort of works because the message sending function checks the receiver and if it is nil it just returns 0, whic will be interpreted by the caller depending on the return type it is expecting e.g. if it expects an int, it will get 0, if it expects a Bool it will get false, if it expects an id, it will get nil.

nil in Swift, as stated above, nil is syntactic sugar for one value of the Optional enum.

enum Optional<T>
{
    case some(T)
    case none
}

Optional is a type in its own right and you cannot call methods of the wrapped type on it, which is why you have to first unwrap it with the ? post fix operator.

Upvotes: 5

Related Questions