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

arkmannj

macrumors 68000
Original poster
Oct 1, 2003
1,765
562
UT
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.

Code:
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 :/
 
Last edited:
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.
 
  • Like
Reactions: arkmannj
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.