Swift, Apple's powerful programming language, offers a rich set of data types to represent various kinds of values. Understanding these types is crucial for effective Swift development.
Integers are whole numbers without fractional components. Swift provides signed and unsigned integers of various sizes.
let age: Int = 30
let unsignedValue: UInt = 42
For decimal numbers, Swift offers two floating-point types: Double (64-bit) and Float (32-bit).
let pi: Double = 3.14159
let height: Float = 1.75
Booleans represent true or false values, essential for conditional logic.
let isSwiftAwesome: Bool = true
Strings are sequences of characters, used for text representation.
let greeting: String = "Hello, Swift!"
Arrays store ordered collections of values of the same type. Learn more about Swift Arrays.
let fruits: [String] = ["Apple", "Banana", "Orange"]
Sets are unordered collections of unique values. Explore Swift Sets for more details.
let uniqueNumbers: Set = [1, 2, 3, 4, 5]
Dictionaries store key-value pairs. Dive deeper into Swift Dictionaries.
let capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo"]
Swift is a type-safe language, meaning it helps you be clear about the types of values your code can work with. It also features powerful Type Inference, often allowing you to omit explicit type annotations.
You can explicitly declare a variable's type using type annotations:
var score: Int = 0
Swift can often infer the type based on the initial value:
var name = "Alice" // Swift infers this as String
Optionals are a powerful feature in Swift, allowing you to represent the absence of a value. They add a layer of safety to your code by forcing you to handle potential nil values explicitly.
var optionalName: String? = nil
optionalName = "Bob"
Understanding Swift data types is fundamental to writing efficient and error-free code. As you progress, explore more advanced topics like Enumerations and Structures to further enhance your Swift programming skills.