Working with Data Types
1. Using Integer Types
| Type | Size | Range | Description |
|---|---|---|---|
| Int | 64 bits |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Platform-dependent signed integer type |
| Int8 | 8 bits |
-128 to 127 |
Signed 8-bit integer |
| Int16 | 16 bits |
-32,768 to 32,767 |
Signed 16-bit integer |
| Int32 | 32 bits |
-2,147,483,648 to 2,147,483,647 |
Signed 32-bit integer |
| Int64 | 64 bits |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Signed 64-bit integer |
| UInt | 64 bits |
0 to 18,446,744,073,709,551,615 |
Platform-dependent unsigned integer type |
| UInt8 | 8 bits |
0 to 255 |
Unsigned 8-bit integer |
| UInt16 | 16 bits |
0 to 65,535 |
Unsigned 16-bit integer |
| UInt32 | 32 bits |
0 to 4,294,967,295 |
Unsigned 32-bit integer |
| UInt64 | 64 bits |
0 to 18,446,744,073,709,551,615 |
Unsigned 64-bit integer |
Example: Integer Literal Conversion
let integerLiteral = 42
let int8Value: Int8 = 127
let int32Value: Int32 = 2_147_483_647
let uintValue: UInt = 1000
Example: Integer Type Casting
let int16Value: Int16 = 32767
let int32Value: Int32 = Int32(int16Value) // Explicit cast
let int64Value: Int64 = 9223372036854775807
let uintValue: UInt = UInt(int64Value)
2. Using Unsigned Integer Types
| Type | Size | Range | Description |
|---|---|---|---|
| UInt8 | 8 bits |
0 to 255 |
Unsigned 8-bit integer, ideal for small values like pixel colors or array indices. |
| UInt16 | 16 bits |
0 to 65,535 |
Unsigned 16-bit integer, useful for larger values or memory addresses. |
| UInt32 | 32 bits |
0 to 4,294,967,295 |
Unsigned 32-bit integer, suitable for large numbers or counters. |
| UInt64 | 64 bits |
0 to 18,446,744,073,709,551,615 |
Unsigned 64-bit integer, for very large numbers or large data sizes. |
Example: Using UInt8 for RGB Color Components
let red: UInt8 = 255
let green: UInt8 = 128
let blue: UInt8 = 0
let color = (red: red, green: green, blue: blue)
print("Color: R=\(color.red), G=\(color.green), B=\(color.blue)")
Example: Converting Int to UInt
let signedValue: Int = -5
let unsignedValue: UInt = UInt(signedValue) // Result: 4294967291 (if Int is 32-bit)
print("Converted value: \(unsignedValue)")
3. Using Floating-Point Types
| Type | Size | Range | Description |
|---|---|---|---|
| Float | 32 bits |
±1.4 × 10⁻⁴⁵ to ±3.4 × 10³⁸ | Single-precision floating-point type |
| Double | 64 bits |
±4.9 × 10⁻³²⁴ to ±1.8 × 10³⁰⁸ | Double-precision floating-point type |
Example: Declaring and Using Float Values
let pi: Float = 3.14159
let radius: Float = 5.0
let area = pi * radius * radius
print("Area: \\(area)")
Example: Declaring and Using Double Values
let gravitationalConstant: Double = 6.67430e-11
let mass1: Double = 5.972e24
let mass2: Double = 7.348e22
let distance: Double = 3.844e8
let force = gravitationalConstant * (mass1 * mass2) / (distance * distance)
print("Gravitational Force: \\(force)")
Note:
Float and Double types can represent fractional values but may have precision limitations due to binary floating-point representation.
Warning: Be cautious when comparing floating-point numbers for equality; use tolerance-based comparisons instead.
4. Working with Boolean
| Property | Description | Example |
|---|---|---|
| Bool | Boolean type with values true or false | let isActive: Bool = true |
| true / false | Literal values for Boolean type | let isComplete = false |
Example: Boolean Operations
let a = true
let b = false
let andResult = a && b
let orResult = a || b
let notResult = !a
Example: Conditional with Boolean
let hasPermission = true
if hasPermission {
print("Access granted")
} else {
print("Access denied")
}
Note: Swift's Bool type is not interchangeable with integers or other numeric types.
5. Working with Strings
| Property | Description | Example |
|---|---|---|
| String | Immutable sequence of characters | let greeting = "Hello, World!" |
| String.init | Initialize a new string | let empty = String() |
| String.count | Number of characters in a string | greeting.count |
| String.isEmpty | Check if string is empty | greeting.isEmpty |
| String.hasPrefix | Check if string starts with a substring | greeting.hasPrefix("Hello") |
| String.hasSuffix | Check if string ends with a substring | greeting.hasSuffix("World!") |
| String.uppercased | Convert string to uppercase | greeting.uppercased() |
| String.lowercased | Convert string to lowercase | greeting.lowercased() |
| String.replacingOccurrences | Replace occurrences of a substring | greeting.replacingOccurrences(of: "World", with: "Swift") |
| String.components(separatedBy:) | Split string into array using separator | "a,b,c".components(separatedBy: ",") |
Example: String Interpolation
let name = "Alice"
let age = 30
let message = "Hello, I'm \(name) and I am \(age) years old."
Example: String Concatenation
let first = "Swift"
let second = "Programming"
let combined = first + " " + second
Example: Substring Access
let text = "Hello, Swift!"
let firstChar = text[..<text.index(text.startIndex, offsetBy: 1)]
let lastChar = text[text.index(text.endIndex, offsetBy: -1)...]
Example: Unicode and Emoji Support
let emoji = "🚀 Swift 🌍"
print(emoji.count) // Counts grapheme clusters, not bytes
let firstGrapheme = emoji[emoji.startIndex]
let lastGrapheme = emoji[emoji.index(emoji.endIndex, offsetBy: -1)]
6. Using Type Aliases
Type aliases provide a way to create an alternative name for an existing type in Swift. They are useful for improving code readability and maintainability, especially when working with complex types.
| Type Alias | Original Type | Description |
|---|---|---|
| AliasName | OriginalTypeName |
Represents a more readable or concise name for a type. |
Example: Defining and Using Type Aliases
typealias Age = Int
typealias Name = String
typealias PersonInfo = (name: Name, age: Age)
let person: PersonInfo = (name: "Alice", age: 30)
print("Name: \(person.name), Age: \(person.age)")
Note: Type aliases do not create new types; they are simply alternative names for existing types.
Key Points
- Type aliases improve code clarity by giving meaningful names to complex types.
- They are not runtime types but compile-time constructs.
- Use
typealiaskeyword to define a type alias.
7. Converting Between Types
| Conversion Type | Description | Example |
|---|---|---|
| Implicit Conversion | Automatic conversion between compatible types by the compiler | |
| Explicit Conversion | Manual conversion using type casting operators | |
| Type Casting with as? | Safely cast to a different type, returns optional | |
| Type Casting with as! | Force cast to a different type, crashes if invalid | |
Example: Type Conversion in Functions
func calculateArea(width: Double, height: Double) -> Double {
return width * height
}
let intWidth = 10
let intHeight = 5
let area = calculateArea(width: Double(intWidth), height: Double(intHeight))
print("Area is \(area)") // Prints "Area is 50.0"
8. Checking Type Information
| Method | Description | Return Value | Notes |
|---|---|---|---|
| type(of:) | Gets the dynamic type of a value | Any.Type |
Useful for runtime type checking |
| isinstanceof | Checks if an object is an instance of a class | Bool |
Available in Swift through is operator |
| as? | Safe downcast to a specific type | Optional<Type> |
Returns nil if cast fails |
| as! | Forced downcast to a specific type | Type |
Crashes if cast fails; use with caution |
Example: Using type(of:)
let number = 42
let type = type(of: number)
print(type) // Int.self
let text = "Hello"
let type2 = type(of: text)
print(type2) // String.self
Example: Using is operator
let value: Any = "Swift"
if value is String {
print("It's a string")
} else {
print("Not a string")
}
Example: Safe casting with as?
let values: [Any] = [1, "two", 3.0]
for value in values {
if let str = value as? String {
print("Found string: \\(str)")
} else if let num = value as? Int {
print("Found int: \\(num)")
}
}
9. Using Any and AnyObject
| Type | Description | Usage |
|---|---|---|
| Any | Represents any value from any type, including optionals and non-optional types. | Used for storing values of unknown or mixed types in collections or function parameters. |
| AnyObject | Represents any instance of a class type. | Used for working with instances of classes in a type-erased way, particularly useful in Objective-C interop. |
Example: Using AnyObject with Class Instances
class MyClass { var value = 10 }
let instances: [AnyObject] = [MyClass(), MyClass()]
let firstInstance = instances[0] as! MyClass
Note:
Any can hold values of any type, including optionals. Using AnyObject is preferred when working with class instances to avoid unnecessary boxing of value types.
10. Understanding Value vs Reference Types
| Type | Behavior | Examples | Memory Allocation |
|---|---|---|---|
| Value Types | Each variable has its own copy; changes to one don't affect others. | Int, String, Array, Dictionary |
Stack allocated |
| Reference Types | Variables point to the same memory location; changes affect all references. | Class, Array (when used with class), Dictionary (when used with class) |
Heap allocated |
Example: Value Type Behavior
var a = 10
var b = a
b = 20
print(a) // Output: 10
print(b) // Output: 20
Example: Reference Type Behavior
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"
print(person1.name) // Output: Bob
print(person2.name) // Output: Bob
11. Working with Numeric Literals
| Literal Type | Examples | Description |
|---|---|---|
| Integer | 42 |
Whole number without decimal point |
| Floating-point | 3.14, 2.0e10 |
Number with decimal point or scientific notation |
| Binary | 0b1010 |
Base-2 literal prefixed with 0b |
| Octal | 0o755 |
Base-8 literal prefixed with 0o |
| Hexadecimal | 0xFF |
Base-16 literal prefixed with 0x |
Example: Numeric Literal Usage
let integerLiteral = 42
let floatLiteral = 3.14
let binaryLiteral = 0b1010
let octalLiteral = 0o755
let hexLiteral = 0xFF
print(integerLiteral) // 42
print(floatLiteral) // 3.14
print(binaryLiteral) // 10
print(octalLiteral) // 493
print(hexLiteral) // 255
Note: Swift allows underscores in numeric literals for readability:
let largeNumber = 1_000_000