What is typecasting?
What is typecasting?
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.
isThe 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:
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.
asSwift provides three variations of the as operator for type casting:
as for upcastingas? for optional downcastingas! for forced downcastingasUpcasting 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:
class Animal {
var name: String
init(name: String) { self.name = name }
Đă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.