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

What is typecasting?

Câu trả lời

Typecasting in Swift is the process of converting an instance of one type to another within the same class hierarchy. This is essential for runtime type checking and safe downcasting of instances to subclass types. Swift provides two main operators for typecasting: is and as.

Type Checking with is

The is operator is used to check whether an instance belongs to a specific type. It returns true if the instance is of the specified type and false otherwise.

Example:

swift Copy
let myInstance: Any = 42
if myInstance is Int {
    print("myInstance is an Int")
} else {
    print("myInstance is not an Int")
}
// Output: myInstance is an Int

In this example, the is operator checks if myInstance is of type Int.

Type Casting with as

Swift provides three variations of the as operator for type casting:

  • as for upcasting
  • as? for optional downcasting
  • as! for forced downcasting

Upcasting with as

Upcasting is the conversion of a subclass instance to its superclass type. This is always safe and does not require explicit syntax in most cases.

Example:

swift Copy
class Animal {
    var name: String
    init(name: String) { self.name = name }
    func makeSound() { print("Animal sound") }
}

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

let dog = Dog(name: "Fido")
let animal: Animal = dog // Upcasting
print(animal.name) // Output: Fido
animal.makeSound() // Output: Woof

In this example, a Dog instance is upcast to an Animal instance.

Optional Downcasting with as?

Optional downcasting attempts to cast an instance to a subclass type and returns an optional value. If the downcast fails, it returns nil.

Example:

swift Copy
let animal: Animal = Dog(name: "Fido")
if let dog = animal as? Dog {
    dog.makeSound() // Output: Woof
} else {
    animal.makeSound()
}

Here, the as? operator tries to downcast animal to Dog. If successful, it calls Dog's makeSound method.

Forced Downcasting with as!

Forced downcasting att...

middle

middle

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

middle

When should I use deinit ?

junior

What is a Serial Queue?

senior

What’s the difference between a static variable and a class variable?

Bình luận

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

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