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

Explain when to use differe...

Câu trả lời

In Swift, type casting is a powerful feature that allows you to check the type of an instance or to treat that instance as a different type within its class hierarchy. Swift provides several casting operators, each with specific use cases:

as Operator

  • Purpose: Used for upcasting, which is the process of treating a subclass instance as an instance of its superclass.
  • Usage: This operator is typically used implicitly, meaning you often don't need to write it explicitly in your code.
  • Example:
    let someObject: ParentClass = ChildClass()
    let anotherObject = someObject as ParentClass
  • When to Use: Use as when you need to treat a subclass instance as its superclass type. This is common when you want to store different subclass instances in a collection that expects the superclass type.

as? Operator

  • Purpose: Used for conditional downcasting, which attempts to cast an instance to a subclass type and returns an optional value.
  • Usage: This operator is safe because it returns nil if the cast fails, avoiding runtime errors.
  • Example:
    let someObject: ParentClass = ChildClass()
    let childObject = someObject as? ChildClass
  • When to Use: Use as? when you are not sure if the cast will succeed and you want to handle the possibility of failure gracefully. This is useful in scenarios where the type of the instance is not known at compile time.

as! Operator

  • Purpose: Used for forced downcasting, which attempts to cast an instance to a subclass type and forcefully unwraps the result.
  • Usage: This operator should be used with caution because it will cause a runtime error if the cast fails.
  • Example:
    let someObject: ParentClass = ChildClass()
    let childObject = someObject as! ChildClass
  • When to Use: Use as! when you are certain that the cast will succeed. This is typically used in situations where you have already checked the type using the is operator or other means.

is Operator

  • Purpose: Used for type checking, which checks whether an instance is of a certain type.
  • Usage: This operator returns a Boolean value indicating whether the instance can be cast to the specified type.
  • Example:
    let someObject: ParentClass = ChildClass()
    if someObject is ChildClass {
        print("Instance is ChildClass")
    }
  • When to Use: Use is when you nee...
senior

senior

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

middle

How to sort array of custom objects by property value in Swift?

senior

What is the difference between fileprivate and private ?

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