How optional in swift is different from nil pointer in objective c?
-
2well its mostly opinion based, this might help http://stackoverflow.com/questions/35546224/what-advantage-of-using-optional-in-swift-over-nil-in-objective-c – Mayank Baiswar Jul 29 '16 at 04:17
2 Answers
A Swift optional is not a nil value. It is a sort of enum where one case represents a non-value (similar to NULL in a relational database), and the other represents an actual value.
Writing if myOptional == nil ...
is just the syntax for checking if the optional is set to the non-value case.
A simple proof that the non-value case isn't nil is that optionals apply to all types, including simple integers.

- 7,469
- 2
- 21
- 22
Well,
In defintion terms:
Swift optional variable is an enum, which can have nil as a value, where as objective variable is a pointer, where nil represents, it is pointing no where.
In Usage terms:
Both are somewhat similar in the sense,
that both variables having nil value on messaging any method returns nil
Optional chaining in Swift is similar to messaging nil in Objective-C, but in a way that works for any type, and that can be checked for success or failure.
But in Safety Checking, Swift optional is the winner
As compiler does many type checking for you already, Ex. non optional parameter can't accept optional, thus you will need to unwrap it by first checking it for nil Or when you you cast any variable, it always returns an optional, thus again a safety feature at compiler level

- 1
- 1

- 2,578
- 20
- 28