Welcome to the exciting world of Swift! Today, we're diving into one of the crucial concepts - Type-Casting Patterns. Let's explore how to work with different data types in Swift. 💡
Type-casting is the process of converting data from one type to another in Swift. It's essential when you want to perform operations that aren't supported between different data types.
Implicit type-casting happens automatically when Swift can safely convert one type to another. For example, Swift will convert an Int to a Double when multiplied by a Double.
let a = 5
let b = 3.14
let c = a * b // c is of type Double, Swift automatically converts a to Double
print(c) // Output: 15.7Explicit type-casting is when we manually convert data from one type to another using type casting operators.
let d: Double = 3.14
let e: Int = Int(d) // Converting Double to Int explicitly
print(e) // Output: 3Forced casting, also known as downcasting, is used to convert a superclass instance to a subclass. However, it's important to remember that you can only downcast when the instance is actually of the subclass type.
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var breed: String
init(name: String, breed: String) {
self.breed = breed
super.init(name: name)
}
}
let pet = Dog(name: "Rex", breed: "Labrador")
let animal = pet as! Animal // downcasting Dog to Animal
print(animal.name) // Output: RexSwift provides optional types Optional<Wrapped> to handle cases where a variable's value can be either present or absent.
let str: String? = "Hello, World!"
let num: Int? = nil
let strInt: Int? = Int(str ?? "")
print(strInt) // Output: Some 734820473
let numStr: String? = String(num ?? 0)
print(numStr) // Output: Some "0"What happens when we multiply an `Int` by a `Double` in Swift?
What is the output of the following code?