What’s the difference between a static variable and a class variable?
What’s the difference between a static variable and a class variable?
In Swift, both static and class keywords are used to define type-level properties and methods, meaning they belong to the type itself rather than to instances of the type. However, there are key differences between them, particularly in terms of inheritance and mutability.
static variable is a type-level property that is shared across all instances of the type. It is defined using the static keyword.Static variables cannot be overridden by subclasses. This means that the value of a static variable is the same across the entire class hierarchy.Static variables are typically used for constants or properties that should not change and should be consistent across all instances of the class or struct.class Person {
static var species = "Homo sapiens"
}
print(Person.species) // Output: Homo sapiens
class variable is also a type-level property, but it is defined using the class keyword.Class variables can be overridden by subclasses. This allows subclasses to provide their own implementation or value for the property.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.