Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
In Swift, type safety is a core principle, meaning you can't inadvertently mix types or use one type in place of another without an explicit conversion. However, there are situations where you might need to convert one data type to another. Let's explore common data type conversions in Swift:
You can convert between different numeric types using initializers of numeric data types:
let intVal: Int = 42 let doubleVal: Double = Double(intVal) let floatVal: Float = Float(intVal)
Do note that these conversions can sometimes be lossy (e.g., converting a Double
to an Int
truncates the decimal portion).
You can convert a String
to a number using initializers, but these initializers are failable, meaning they return an optional (Int?
, Double?
, etc.):
let numberString: String = "123" let intValue: Int? = Int(numberString) // Optional(123) let decimalString: String = "123.45" let doubleValue: Double? = Double(decimalString) // Optional(123.45)
If the string can't be converted to a number, the initializer returns nil
.
This is straightforward and uses the String
initializer:
let myInt: Int = 42 let intAsString: String = String(myInt) let myDouble: Double = 42.42 let doubleAsString: String = String(myDouble)
Unlike some other languages, Swift doesn't allow implicit conversion to or from Bool
. You must handle conversions explicitly:
let truthyValue: Int = 1 let isTrue: Bool = (truthyValue != 0) // true
For collections like arrays and dictionaries, you can use the map
function or similar higher-order functions to transform elements:
let stringNumbers = ["1", "2", "3"] let integers = stringNumbers.compactMap { Int($0) } // [1, 2, 3]
compactMap
is used here to filter out any potential nil
values.
If you're working with class hierarchies or protocols, you might use the as?
and as!
operators to downcast:
class Animal {} class Dog: Animal {} let rex = Dog() if let dog = rex as? Dog { print("It's a dog!") }
You can also use is
to check type:
if rex is Dog { print("It's a dog!") }
Remember that Swift highly values type safety, so many of these conversions, especially between unrelated types, require explicit action on your part. Always ensure that your conversions make sense in the context of your program to maintain clarity and correctness.
Swift data type conversion examples:
let intNumber = 42 let doubleNumber = Double(intNumber)
Type casting in Swift:
let value: Any = 42 if let intValue = value as? Int { print("It's an integer: \(intValue)") }
Swift convert Int to String:
String()
to convert an Int
to a String
.let intValue = 42 let stringValue = String(intValue)
How to convert String to Int in Swift:
Int()
to convert a String
to an Int
.let stringValue = "42" if let intValue = Int(stringValue) { print("Converted to integer: \(intValue)") }
Swift float to int conversion:
Int()
to convert a Float
to an Int
.let floatValue = 42.5 let intValue = Int(floatValue)
Type inference in Swift:
let inferredString = "Hello, Swift!" // Type inferred as String
Swift convert double to int:
Int()
to convert a Double
to an Int
.let doubleValue = 42.7 let intValue = Int(doubleValue)
Implicit and explicit type conversion in Swift:
let implicitInt: Int = 42 let explicitDouble: Double = Double(implicitInt)
Swift convert array to set:
Set()
to convert an array to a set.let array = [1, 2, 3, 3, 4, 5] let set = Set(array)
Working with optionals in Swift:
var optionalValue: Int? = 42 if let unwrappedValue = optionalValue { print("Value is present: \(unwrappedValue)") } else { print("Value is nil") }
Swift convert string to date:
DateFormatter
to convert a string to a date.let dateString = "2023-01-01" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" if let date = dateFormatter.date(from: dateString) { print("Converted to date: \(date)") }
Type safety in Swift:
var integerValue: Int = 42 // The following line will result in a compilation error: // integerValue = "Hello, Swift!"
Swift convert string to array:
map
to convert a string to an array of characters.let stringValue = "Swift" let charArray = stringValue.map { $0 }
Converting between Swift data types:
let intToString = String(42) let stringToInt = Int("42")
Handling nil values in Swift:
var optionalValue: Int? = nil // Use optional binding to safely unwrap the value if let unwrappedValue = optionalValue { print("Value is present: \(unwrappedValue)") } else { print("Value is nil") }