Any 'rule of thumb' about optionals?

Discussion in 'iOS Programming' started by 1458279, Dec 31, 2015.

  1. 1458279 Suspended

    1458279

    Joined:
    May 1, 2010
    Location:
    California
    #1
    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?
     
  2. grandM macrumors 6502a

    grandM

    Joined:
    Oct 14, 2013
    #2
    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
     
  3. Mascots macrumors 65816

    Mascots

    Joined:
    Sep 5, 2009
    #3
    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.
     

Share This Page