开发者

Why do functions use -(void) and not -(nil) in Obj-C?

开发者 https://www.devze.com 2023-02-20 06:14 出处:网络
In objective-C I often see functions that don\'t return anything declared as: - (void)myFunction {…

In objective-C I often see functions that don't return anything declared as:

 - (void)myFunction {…

But why aren't functions declared using n开发者_StackOverflow中文版il, like this

 - (nil)myFunction {…

Don't they both return "nothing"?


void is nothing. nil is something (0).

In other words, returning nil isn't the same as returning nothing.


Historically in languages belonging (syntactically) to the C-like language family, void indicates that there is no type being returned from a function.

More precisely, just as variables have (or belong to) a given type, functions also have types. For example, a function that returns a int, it is an int type function, or a function whose type is int. Same if it returns something else.

If the function does not return anything - it returns nothing - what type does it belongs to? It has no type, and the void type represents such a thing.

I'm not versed in Objective C, but if I understand correctly, nil is an typeless ID (or an id of any type), almost like a built-in implementation of the null pattern.

And null is a (void *) type, the later being a typeless pointer that can point to anything, just as it would in C and C++.

So a function that returns nil would imply that its type is an id of any type. Don't know if that even makes sense. So right then and there, (nil)myFunction is of a type completely different from (void)myFunction since the former has one type (any type?) whereas the later has no type at all.

Also, nil is a built-in constant. Returning nill is like saying that your function returns a specific number for instance ((1)myFunction). That wouldn't make any sense, would it?


Void is an object type. Void means there is no return value.
Nil is an object, not a type. It represents an empty value.

0

精彩评论

暂无评论...
验证码 换一张
取 消