BudiBadu Logo
Samplebadu

Swift by Example: Variables

Swift 5.x

Learn Swift variable declaration and mutability with this sample code demonstrating type inference, explicit type annotations, string interpolation, and optional types for handling nil values safely in your applications.

Code

// Variable declaration using 'var'
var message = "Hello, Swift!"
message = "Hello, World!" // Can be changed

// Type inference
var count = 42 // Inferred as Int
var price = 19.99 // Inferred as Double

// Explicit type annotation
var name: String = "Alice"
var isActive: Bool = true

// String interpolation
print("Message: (message), Count: (count)")

// Optionals (variables that can be nil)
var optionalName: String? = "Bob"
optionalName = nil

Explanation

In Swift, variables are declared using the var keyword. Variables are mutable, meaning their values can be changed after they are initialized. Swift is a strongly typed language, but it heavily relies on type inference. This means you often don't need to specify the type if the compiler can figure it out from the initial value.

However, you can explicitly specify the type using a colon, like var name: String. This is useful when you initialize a variable later or when the inferred type isn't what you want (e.g., you want a Float instead of a Double). String interpolation is done using (variable) inside a string literal.

Swift introduces the concept of Optionals to handle the absence of a value. A variable of type String cannot be nil. To allow it to be nil, you must declare it as an optional using a question mark, like String?. This safety feature prevents null pointer exceptions, a common source of bugs in other languages.

Type safety is a core principle in Swift. The compiler enforces that variables contain only values of their declared type, catching many errors at compile time rather than runtime. This makes Swift code more predictable and easier to debug.

Code Breakdown

2
var creates a mutable variable that can be reassigned.
6
count = 42 uses type inference to determine Int type.
10
name: String explicitly specifies the type annotation.
17
String? defines an optional type that can hold a string or be nil.