(edit: apologies to Patrick ... i found out i was was posting my response just a few minutes after he was completing his post -- he beat the clock on me!.)
hi,
Can't I do exactly that by writing this code? This won't cause an error and this is using a non-static property within a static method:
the reason that this code works:
let fan = TaylorFan(name: "James", age: 25, favoriteSong: "Shake It Off")
TaylorFan.dance() // This will print, "Let's dance to Shake It Off!"
is that fan
is declared as a global ("at the top level of your code"), so the value of fan
is available when you call TaylorFan.dance()
.
on the other hand, if you had a function such as
func printFanDance() {
let fan = TaylorFan(name: "James", age: 25, favoriteSong: "Shake It Off")
TaylorFan.dance()
}
you have a problem, because fan
is local to the function; it's not accessible to the static function Taylor.dance
.
I would like to double check that I have this correct ...
i think you have this right, unless someone wants to parse your question more carefully than i have.
in effect, a static function is just a global function that lives in the namespace of the defining struct or class. if you define something like
class MyWhateverClass {
static func doSomethingWith(_ x: Double) {
print(x)
}
}
then these two statement are effectively the same:
print(3.3)
and
MyWhateverClass.doSomethingWith(3.3)
i think that might help,
DMG