Data types in swift?
Answer
Overview
Swift is Apple's programming language for iOS, macOS, watchOS, and tvOS development. It has a rich, type-safe system with both value types (struct-based) and reference types (class-based).
Swift Data Types
Basic Types
swift// Integer types var age: Int = 25 // Platform-native (64-bit on modern iOS) var byte: Int8 = 127 // -128 to 127 var small: Int16 = 32767 var medium: Int32 = 2_147_483_647 var large: Int64 = 9_223_372_036_854_775_807 // Unsigned var count: UInt = 10 // Unsigned Int var uByte: UInt8 = 255 // Floating point var height: Double = 5.11 // 64-bit (preferred) var price: Float = 9.99 // 32-bit // Boolean var isActive: Bool = true // String var name: String = "Alice" // Multi-line string (triple-quote in Swift) var multiLine = """ Hello, World! """ // Character var letter: Character = "A"
Collections
swift// Array var fruits: [String] = ["apple", "banana", "cherry"] let ages: [Int] = [25, 30, 35] // Dictionary (Map equivalent) var scores: [String: Int] = ["Alice": 95, "Bob": 87] // Set (unique values) var tags: Set<String> = ["swift", "ios", "apple"] // Tuple (multiple values without a struct) let person: (String, Int) = ("Alice", 28) let named = (name: "Bob", age: 30) print(named.name) // Bob
Optional (Nullable)
swiftvar email: String? = nil // Optional -- can be nil var phone: String? = "9876543210" // Unwrapping if let phone = phone { print("Phone: \(phone)") } // Nil coalescing (?? equivalent in Swift) let displayPhone = phone ?? "No phone" // Force unwrap (dangerous -- crash if nil) print(phone!)
Swift vs Dart Type Mapping
| Swift | Dart | Description |
|---|---|---|
text | text | Integer |
text | text | Float 64-bit |
text | -- | Float 32-bit |
text | text | Text |
text | text | Boolean |
text | text | Array |
text | text | Dictionary |
text | text | Unique set |
text | text | Optional/Nullable |
text | text | Multiple values |
text | text | Any type |
Key Difference: Swift has value types (
,textstruct, tuples) and reference types (textenum). Dart's basic types are all objects -- no primitive types.textclass