What’s the difference between a st...
What’s the difference between a st...
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.Class
variables are used when you want to allow subclasses to customize or override the property.class Person {
class var species: String {
return "Homo sapiens"
}
}
class Human: Person {
override class var species: String {
return "Homo sapiens sapiens"
}
}
print(Person.species) // Output: Homo sapiens
print(Human.species) // Output: Homo sapiens sapiens
class
variables can be overridden by subclasses, while static
variables cannot be overridden.static
and class
variables can be mutable or immutable, but the mutability does not affect their ability to be overridden.static
when you want a property to be consistent and unchangeable across the entire class hierarchy. Use class
when you want to allow subclasses to provide their own implementation or value.Static
methods and properties are statically dispatched, meaning the compiler knows at compile tim...senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào