What is the difference between st...
What is the difference between st...
In Swift, both static func
and class func
are used to define type methods, which are methods that belong to the type itself rather than to instances of the type. However, there are key differences between the two:
Usage Context:
static func
: This keyword is used to define type methods for structs, enums, and classes. When used in a class, the method cannot be overridden by subclasses.class func
: This keyword is used exclusively in classes and protocols. It allows the method to be overridden by subclasses, enabling polymorphic behavior.Inheritance and Overriding:
static func
: Methods defined with static
are final and cannot be overridden by subclasses. This is useful when you want to ensure that the method's implementation remains consistent across all subclasses.class func
: Methods defined with class
can be overridden by subclasses. This allows subclasses to provide their own implementation of the method, which is essential for polymorphism.Example:
static func
:
struct Math {
static func square(number: Int) -> Int {
return number * number
}
}
let result = Math.square(number: 4)
print(result) // 16
class func
:
class Vehicle {
class func description() -> String {
return "A vehicle"
}
}
class Car: Vehicle {
o...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào