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

What is the difference between Upcast and Downcast in Swift?

Câu trả lời

In Swift, upcasting and downcasting are two fundamental concepts related to type casting within an inheritance hierarchy. Here’s a detailed explanation of the differences between them:

Upcasting

Definition: Upcasting is the process of converting a subclass instance to its superclass type. This is generally done implicitly by the Swift compiler.

Usage: Upcasting is used when you want to treat an instance of a subclass as an instance of its superclass. This is useful for writing generic code that can handle different types of objects through a common interface.

Safety: Upcasting is always safe because every subclass instance is also an instance of its superclass. Therefore, no runtime checks are needed.

Syntax: The as operator is used for upcasting, although it is often implicit and not explicitly required in code.

Example:

swift Copy
class Animal {
    func makeSound() {
        print("Animal sound")
    }
}

class Dog: Animal {
    override func makeSound() {
        print("Woof")
    }
}

let dog = Dog()
let animal: Animal = dog // Upcasting
animal.makeSound() // Output: Woof

In this example, the Dog instance is upcasted to an Animal type, allowing it to be treated as an Animal.

Downcasting

Definition: Downcasting is the process of converting a superclass instance back to a subclass type. This is done explicitly and can fail if the instance is not actually of the subclass type.

Usage: Downcasting is used when you need to access the specific properties or methods of a subclass that are not available in the superclass.

Safety: Downcasting can be unsafe because it may lead to runtime errors if the instance being cast is not of the expected subclass type. Therefore, Swift provides two forms of downcasting: optional downcasting (as?) and forced downcasting (as!).

Syntax:

  • as? (Optional Downcasting): Returns an optional value. If the downcast fails, it returns nil.
  • as! (Forced Downcasting): Force-unwraps the result. If the downcast fails, it causes a runtime error.

Example:

swift Copy
let animal: Animal = Dog()

if let dog = animal as? Dog { // Optional Downcasting
    dog.makeSound() // Output: Woof
} else {
    print("Downcasting failed")
}

let forcedDog = animal as! Dog // Forced Downcasting
forcedDog.makeSound() /...
junior

junior

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

expert

Explain what is DispatchGroup?

expert

What’s the difference between init?() and init() ?

middle

What's the difference between Self vs self ?

Bình luận

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

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