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

What is difference between as? , as! and as in Swift?

Câu trả lời

In Swift, the as?, as!, and as operators are used for type casting, but they serve different purposes and have distinct behaviors:

as? (Optional Casting)

The as? operator is used for conditional casting. It attempts to cast an instance to a specified type and returns an optional value. If the cast is successful, the result is an optional containing the value; if it fails, the result is nil.

Example:

swift Copy
let myVehicle: Any = Car(name: "My Car", brand: "Tesla")
if let myCar = myVehicle as? Car {
    print("My car's brand is \(myCar.brand)")
} else {
    print("myVehicle is not a Car")
}

In this example, myVehicle is conditionally cast to Car. If the cast succeeds, myCar is non-nil and the brand is printed. If it fails, the else block is executed[2][8].

as! (Forced Casting)

The as! operator is used for forced casting. It attempts to cast an instance to a specified type and forces the cast to succeed. If the cast fails, it results in a runtime error (crash).

Example:

swift Copy
let myVehicle: Any = Car(name: "My Car", brand: "Tesla")
let myCar = myVehicle as! Car
print("My car's brand is \(myCar.brand)")

In this example, myVehicle is forcibly cast to Car. If myVehicle is not actually a Car, the program will crash[2][8].

as (Upcasting)

The as operator is used for upcasting, which is casting to a superclass or protocol type. This type of casting is always safe and does not change the actual type of the instance.

Example:

swift Copy
class Vehicle {
    var name: String
    init(name: Str...
middle

middle

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

senior

What's wrong with this code?

middle

What is the difference between a computed property and a property set to a closure?

middle

What is trailing closure syntax?

Bình luận

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

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