How nil can call functions in Objective-C and Swift

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

In Objective-C

nil

represents the absence of an Objective-C object. in detail id

- a pointer to any objects. nil

id

which indicates nothing.

So any primitive types cannot be nils

eg.

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

      

In Swift

nil

represents the absence of any data types called optional. so nil

is the type of types optional?

Both languages, any object nil

types can call a function.

For example.

NSString *name = nil;
[a lowercaseString];

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

      

no zero-point exceptions are encountered in both cases.

How to represent nothing and be missing any types you can call the function?

+3


source to share


1 answer


nil is typealias Optional?

Not. nil

is syntactic sugar for Optional<T>.none

, where T

is an optional-wrapped type.

name: String? = nil 
name.lowercased()

      

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

name?.lowercased()
//  ^ here

      

which basically means the name is not null, expand 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 just 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 seems to work because the send message function checks the receiver and if it is zero it just returns 0 which will be interpreted by the caller depending on the return type expected, for example if it expects an int, it will get 0, if it expects Bool to get false, if it expects an id it will be zero.

nil in Swift, as above, nil is syntactic sugar for a single optional enum value.

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

      

Optional is a type in its own right, and you cannot call methods of a wrapped type on it, so you must first expand it with? post fix.

+4


source







All Articles