Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

1458279

Suspended
Original poster
May 1, 2010
1,601
1,521
California
Does someone have a simple rule of thumb about usage of optional?

It keeps popping up in these tutorials and it seems a bit confusing.

Correct me where I'm wrong:

So an optional is var that might be nil at the time you are accessing it.
If a var might be nil, you must use a ?

You unwrap a var with the !

So what if something is nil and you don't use the optional ?

What happens if something is an optional and you don't do a forced unwrap

What happens if you assign an optional to something that's not an optional

If you assign a non optional to an optional, there is no problem, right?
 
Does someone have a simple rule of thumb about usage of optional?

It keeps popping up in these tutorials and it seems a bit confusing.

Correct me where I'm wrong:

So an optional is var that might be nil at the time you are accessing it.
If a var might be nil, you must use a ?

You unwrap a var with the !

So what if something is nil and you don't use the optional ?

What happens if something is an optional and you don't do a forced unwrap

What happens if you assign an optional to something that's not an optional

If you assign a non optional to an optional, there is no problem, right?
I might be mistaken but an optional is an enum with 2 possible cases being nil or a value
If it might be nil you need an optional
As the optional shields the value or nil it must be unwrapped. If it contains nil you will crash.
- So what if something is nil and you don't use the optional ?
I think you cannot assign it. Not sure though.
- What happens if something is an optional and you don't do a forced unwrap
An optional is returned.
- What happens if you assign an optional to something that's not an optional
You will get an error that you cannot assign it.
- If you assign a non optional to an optional, there is no problem, right
Correct
 
  • Like
Reactions: Mascots
- So what if something is nil and you don't use the optional ?
I think you cannot assign it. Not sure though.

With very few exceptions, which are the result of working with Objective-C, you will find a nil value hidden under a variable. It's often an edge case when working with a framework that's only been partially transitioned.

A good example is Core Data optionals from the database - By default, generated subclasses don't account for swift optional, but the Obj-C runtime is happy to fill, and accept the non-optional value equalling nil.

I forget what happens when working with the value, you may be able to work with it just as you would with Obj-C or weird things may happen when you do encounter a nil value - it's been awhile. To account for it, you just have to mark them as optionals manually.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.