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

What’s the difference between a st...

Câu trả lời

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 Variables

  • Definition: A static variable is a type-level property that is shared across all instances of the type. It is defined using the static keyword.
  • Inheritance: Static variables cannot be overridden by subclasses. This means that the value of a static variable is the same across the entire class hierarchy.
  • Usage: 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.
  • Example:
    class Person {
        static var species = "Homo sapiens"
    }
    
    print(Person.species) // Output: Homo sapiens

Class Variables

  • Definition: A class variable is also a type-level property, but it is defined using the class keyword.
  • Inheritance: Class variables can be overridden by subclasses. This allows subclasses to provide their own implementation or value for the property.
  • Usage: Class variables are used when you want to allow subclasses to customize or override the property.
  • Example:
    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

Key Differences

  1. Overriding: The primary difference is that class variables can be overridden by subclasses, while static variables cannot be overridden.
  2. Mutability: Both static and class variables can be mutable or immutable, but the mutability does not affect their ability to be overridden.
  3. Usage Context: Use 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.

Performance Considerations

  • Static Dispatch: Static methods and properties are statically dispatched, meaning the compiler knows at compile tim...
senior

senior

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

expert

Explain how that code will behave for different Swift versions?

junior

What are Extensions used for in Swift?

senior

Explain the difference between weak and unowned references. Provide an example

Bình luận

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

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