It has destroyed my view about static variables and constant after using swift.
Why swift doesn't allow us to call static variables and constant in other methods?
for example:
class Aa {
static let name = "Aario"
func echo() {
print(name) // Error!
}
}
Mr. ogres told me to use dynamicType
.
class Aa {
static var name = "Aario"
func echo() {
print(self.dynamicType.name)
}
}
let a = Aa()
a.dynamicType.name = "Aario Ai"
a.echo() // it works!!!
It works! So why should I use dynamicType to call static variables?
Finally, the answer is:
class Aa {
static var name = "Static Variable"
var name = "Member Variable"
func echo() {
print(self.dynamicType.name) // Static Variable
print(Aa.name) // Static Variable
print(name) // Member Variable
}
}
let a = Aa()
a.dynamicType.name = "Aario Ai"
Aa.name = "Static: Aario"
a.name = "Member: Aario"
a.echo() // it works!!!
It's really different with other languages.
Static variables have to be addressed with their type, even when you're writing code within this type. See The Swift Programming Language (Swift 2.2) - Properties (in "Querying and Setting Type Properties"):
Type properties are queried and set with dot syntax, just like instance properties. However, type properties are queried and set on the type, not on an instance of that type.
In your code, simply write Aa.name
instead of name
and you'll be fine.