What is difference between as? , as! and as in Swift?
What is difference between as? , as! and as in Swift?
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:
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.
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).
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.