Swift makes you clearly say when you want to change a value from one type to another. This helps avoid mistakes and keeps your code safe.
Type conversion is always explicit in Swift
let newValue = TypeName(oldValue)You write the target type name and put the value you want to convert inside parentheses.
If the conversion is not possible, Swift will give an error or you can use optional conversion.
let intVal = 5 let doubleVal = Double(intVal)
let str = "123" if let number = Int(str) { print(number) }
let pi = 3.14 let intPi = Int(pi)
This program converts a string to an integer explicitly. If the conversion works, it adds 1 and prints the result. If not, it shows an error message.
let ageString = "30" if let age = Int(ageString) { let nextYearAge = age + 1 print("Next year you will be \(nextYearAge) years old.") } else { print("Invalid age input.") }
Swift does not automatically convert types for you. You must always convert explicitly.
Use optional conversion (like Int(string)) when the conversion might fail.
Explicit conversion helps catch errors early and makes your code clearer.
Swift requires you to convert types explicitly to avoid mistakes.
Use the target type name with parentheses to convert values.
Optional conversions help safely handle cases where conversion might fail.
Practice
let x = 5 and let y = 3.2 are different types. What happens if you try to add x + y without conversion?Solution
Step 1: Understand Swift's type safety
Swift requires explicit type conversion to avoid unexpected behavior.Step 2: Check adding Int and Double without conversion
Trying to addIntandDoubledirectly causes a compile-time error.Final Answer:
It causes a compile-time error because Swift does not convert types automatically. -> Option BQuick Check:
Int + Double without conversion causes compile error [OK]
- Assuming Swift converts Int to Double automatically
- Thinking the result is always an Int
- Believing silent conversion happens
num = 10 to a Double in Swift?Solution
Step 1: Recall Swift's explicit conversion syntax
Swift uses the target type name as a function to convert values.Step 2: Identify correct syntax for Int to Double
The correct syntax isDouble(num). Other options are invalid in Swift.Final Answer:
let d = Double(num) -> Option CQuick Check:
Target type as function: Double(num) [OK]
- Using 'as' for numeric conversion
- Calling non-existent methods like toDouble()
- Using custom convert functions not in Swift
let a: Int = 7 let b: Double = 3.5 let c = Double(a) + b print(c)
Solution
Step 1: Convert Int to Double explicitly
ais Int 7, converted to Double 7.0 usingDouble(a).Step 2: Add converted Double and b
Adding 7.0 + 3.5 results in 10.5.Final Answer:
10.5 -> Option AQuick Check:
7.0 + 3.5 = 10.5 [OK]
- Forgetting to convert Int to Double
- Expecting integer addition result
- Assuming implicit conversion
let str = "123" let num = Int(str) let result = num + 10 print(result)
Solution
Step 1: Understand Int initializer returns optional
Int(str)returnsInt?because conversion might fail.Step 2: Adding optional Int and Int causes error
You cannot addInt?andIntdirectly without unwrapping.Final Answer:
Cannot add Int? and Int without unwrapping -> Option DQuick Check:
Int(str) returns Int?, must unwrap before adding [OK]
- Ignoring optional unwrapping
- Assuming Int(str) returns Int directly
- Trying to add optional and non-optional
let arr = ["1", "2", "three", "4"]. You want to convert them to Ints and sum only the valid numbers. Which Swift code correctly does this?Solution
Step 1: Use compactMap to convert and filter valid Ints
compactMapconverts strings to Ints and removes nil values safely.Step 2: Use reduce to sum the valid Ints
reduce(0, +)sums all Ints in the array.Final Answer:
let sum = arr.compactMap { Int($0) }.reduce(0, +) -> Option AQuick Check:
compactMap filters nils, then sum [OK]
- Using map which keeps optionals causing errors
- Force unwrapping without checking validity
- Adding optionals directly without unwrapping
Ready to prove it?
Pass the test and this pattern moves unknown
