To Shadow or Not to Shadow Variables

Variable shadowing is the practice of using the same name for a variable when it appears in different scopes inside the code. For the most part it seems to be taboo, adding to unnecessary confusion inside a project. But two areas it seems not only acceptable, but encouraged.

Variable shadowing in Initializers

struct Building {
    var height: Int
    var location: String
   
    init(height: Int, location: String) {
        self.height = height
        self.location = location
    }
}

let tokyoTower = Building(height: 1092, location: "Tokyo")

Here, the variables height and location are used both as properties and as parameters. I almost always see variable shadowing here, probably because the self keyword makes it clear what is going on.

Variable shadowing in optional binding

var color: String? = "red"

if let color = color {
    print (color)
    //red
}

Here, the original variable color of type Optional String is being bound to a new constant called color. Because you only use the optional once it is unwrapped, it is clear that color is the unwrapped version and not the original optional.

Without variable shadowing, it remains optional.

var color: String? = "red"

if let myColor = color {
    print (color)
    //Optional(red)
}

Back when I talked about creating clean blocks of code for custom views, it seems like it is not common practice to use variable shadowing there. I guess this could cause confusion and/or looks bad.

//Bad variable shadowing?
let label: UILabel = {
  let label = UILabel()
  label.textAlignment = .center
  label.text = "I'm awesome"
  return label
}()

Leave a Comment

Your email address will not be published. Required fields are marked *