← Swift EnglishChapter 02 of 13

Variables and Types

## Learning Objectives - Understand variables (var) and constants (let) - Master Swift data types - Learn type inference - Work with type annotations ## Variables and Constants ### Variables (var) Variables can be changed after initialization: ```swift var age = 25 age = 26 // OK var name = "Alice" name = "Bob" // OK ``` ### Constants (let) Constants cannot be changed after initialization: ```swift let birthYear = 1990 birthYear = 1991 // Error! let pi = 3.14159 pi = 3.14 // Error! ``` ### When to Use Each - Use `let` by default - Use `var` when value must change - Constants enable compiler optimizations ## Data Types ### Integer Types | Type | Size | Range | |------|------|-------| | Int8 | 8-bit | -128 to 127 | | Int16 | 16-bit | -32,768 to 32,767 | | Int32 | 32-bit | -2B to 2B | | Int64 | 64-bit | -9Q to 9Q | | Int | Platform | Depends on platform | | UInt | Unsigned | Platform size | ```swift let positive: UInt = 100 let negative: Int = -50 let defaultInt: Int = 42 ``` ### Floating-Point Types | Type | Size | Precision | |------|------|-----------| | Float | 32-bit | ~6 digits | | Double | 64-bit | ~15 digits | ```swift let floatPi: Float = 3.14 let doublePi: Double = 3.14159265359 // Double is default for floating-point let defaultDouble = 3.14159 // Double ``` ### Boolean ```swift let isSwift: Bool = true let isEasy: Bool = false // Used in conditions if isSwift { print("Swift is great!") } ``` ### String ```swift let greeting: String = "Hello" let name = "World" let combined = greeting + ", " + name + "!" ``` ### Character ```swift let letter: Character = "A" let emoji: Character = "" ``` ## Type Inference Swift infers types when not explicitly declared: ```swift let inferredInt = 42 // Int let inferredDouble = 3.14 // Double let inferredString = "Hi" // String let inferredBool = true // Bool ``` ## Type Annotations Explicitly declare types: ```swift var explicitInt: Int = 100 var explicitDouble: Double = 1.5 var explicitString: String = "Text" var explicitBool: Bool = false ``` ### Multiple Variables ```swift var red, green, blue: Double red = 0.1 green = 0.5 blue = 0.9 ``` ## Type Safety Swift prevents type mismatches: ```swift let count: Int = 10 // count = "ten" // Error: cannot assign String to Int ``` ### Type Conversion ```swift let intValue: Int = 42 let doubleValue: Double = Double(intValue) // 42.0 let doubleNum: Double = 3.14 let intNum: Int = Int(doubleNum) // 3 (truncated) ``` ## Numeric Literals ### Integer Literals ```swift let decimal = 42 // Decimal let hex = 0x2A // Hexadecimal (42) let octal = 0o52 // Octal (42) let binary = 0b101010 // Binary (42) ``` ### Floating-Point Literals ```swift let decimalFloat = 3.14 let exponentFloat = 0.314e1 // 3.14 let hexFloat = 0x1.3p2 // Hex float (4.75) ``` ### Underscores for Readability ```swift let million = 1_000_000 let bytes = 0xFF_E0_00_00 ``` ## Strings and Characters ### String Initialization ```swift let emptyString = "" let anotherEmpty = String() let hello = "Hello" let world = "World" let combined = "\(hello), \(world)!" ``` ### Multiline Strings ```swift let poem = """ Roses are red, Violets are blue, Swift is awesome, And so are you! """ ``` ### Special Characters ```swift let tabbed = "Name\tAge" let newline = "Line1\nLine2" let quote = "She said \"Hello!\"" let backslash = "Path: C:\\Users" ``` ## Tuples Group multiple values: ```swift let httpError = (404, "Not Found") print(httpError.0) // 404 print(httpError.1) // "Not Found" // Named elements let person = (name: "Alice", age: 30) print(person.name) // "Alice" print(person.age) // 30 ``` ### Tuple Decomposition ```swift let (statusCode, message) = httpError print(statusCode) // 404 // Ignore elements let (justCode, _) = httpError ``` ## Type Aliases Create alternative names: ```swift typealias AudioSample = UInt16 typealias Point = (x: Int, y: Int) let maxAmplitude: AudioSample = UInt16.max let origin: Point = (x: 0, y: 0) ``` ## Any and AnyObject ### Any Any type including functions: ```swift var anyValue: Any = 42 anyValue = "String" anyValue = [1, 2, 3] ``` ### AnyObject Any class instance: ```swift var anyObject: AnyObject = NSObject() anyObject = UIView() // On Apple platforms ``` ## Summary - `var` for variables, `let` for constants - Swift has Int, Double, Float, Bool, String, Character - Type inference deduces types automatically - Use type annotations when needed - Tuples group multiple values - `Any` and `AnyObject` for mixed types - Constants (let) are preferred for safety

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →