Câu hỏi phỏng vấn Swift
Câu hỏi

What is the difference between st...

Câu trả lời

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:

  1. 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.
  2. 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.
  3. Example:

    • static func:
      swift Copy
      struct Math {
          static func square(number: Int) -> Int {
              return number * number
          }
      }
      let result = Math.square(number: 4)
      print(result) // 16
    • class func:
      swift Copy
      class Vehicle {
          class func description() -> String {
              return "A vehicle"
          }
      }
      class Car: Vehicle {
          o...
senior

senior

Gợi ý câu hỏi phỏng vấn

expert

What is the use of Hashable protocol?

expert

Why can not we just use weak everywhere and forget about unowned ?

middle

What's the main difference between the Array , Set and Dictionary collection
type?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào