TIL: Swift Global Vars are Functions
I was trying to construct a SwiftUI Preview of a view using:
WeekTasks(weeksData: demoWeeksData)
`demoWeeksData` was defined as a global variable:
var demoWeeksData: [WeekData] = [
WeekData(title: "Walk / Steps", emoji: "🚶♂️", week: [0, 1, 1, 0, 0, 1, 1]),
]
But the Swift compiler said No.
It turns out that global variables in Swift are actually implemented as functions (and as such are computed lazily):
Alex Denisov provides a nice explaination of whats going on on the RailsWare blog.
Joe Groff explains the reasoning behind this on the Swift Forums:
Because global initializers are invoked at the latest on the first load from the global variable, it is true regardless of whether we optimize that programmers cannot rely on the actual point in the program where a global is initialized. You don't control the code that runs before you, and that code may or may not have accessed the variable previously, so you can't reliably point at any one access as the point where the initialization occurs.