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:
      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

senior

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

middle

Explain the difference between DispatchQueue.main.async and DispatchQueue.main.sync ?

senior

What’s the difference between Any and AnyObject ?

middle

What is a good use case for an inout parameter?

Bình luận

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

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