Swift Question about optionals

Discussion in 'iOS Programming' started by arkmannj, Jun 8, 2016.

  1. arkmannj, Jun 8, 2016
    Last edited: Jun 8, 2016

    arkmannj macrumors 65816


    Oct 1, 2003
    I have a very simple question, (Yes I am this new)

    In various books and even in Apple's own Swift documentation I often see examples like this to check if an optional has a value.

    If let MYVar = SomeClass.SomeProperty? {
                                                                   Print("Yay A value")
                                                         else {
                                                                 Print("Sad No Value")
    My question is this. When I use this method aren't I essentially using/allocating more memory to create/store a new constant/variable ("MyVar" in this case) that all I'm using it for is to check an optional?
    Or does Swift know that I'm just using it to check the Optional and just drop the constant/variable (and its value/stored reference) immediately after?

    Edit: Reworded to try and better describe my intent....hopefully :/
  2. mjohnson1212 macrumors member

    Nov 15, 2007
    Optionals are an enum. With the if let you are getting the wrapped value from the optional. You get a reference to the wrapped value so it isn't using more memory just because you unwrapped it.
  3. MarkCollette macrumors 68000


    Mar 6, 2003
    Toronto, Canada
    Also, SomeProperty might have a getter method that has a cost to being called, so it might actually be more performant to access it once and unwrap the optional value, and store it in a local value, and then access that local value repeatedly, instead of repeatedly accessing the property directly.

Share This Page