Swift Basics — Complete Beginner's Guide to Swift Syntax
In this tutorial, you will learn about Swift Basics. We cover key concepts, practical examples, and best practices to help you master this topic.
Swift basics cover the fundamental building blocks of the language: variables and constants declared with var and let, type inference and explicit annotations, the major data types including Int, Double, String, Bool, and Character, string interpolation with backslash-parentheses syntax, basic operators, type conversion, and printing output with print(). This tutorial provides step-by-step guidance with runnable examples.
What You'll Learn
- Declaring variables with var and constants with let
- Understanding type inference vs explicit type annotation
- Working with Int, Double, String, Bool, and Character types
- Using string interpolation for formatting output
- Applying arithmetic, comparison, and logical operators
- Converting between types safely with initializers
- Reading input and printing output
Why It Matters
Every Swift program you will ever write builds on these fundamentals. Constants prevent accidental modification, type inference reduces clutter, and Swift's strong type system catches mismatches at compile time. Mastering these basics is essential before moving to collections, control flow, or object-oriented programming.
Real-World Use
The Doda Browser settings screen uses constants for configuration keys, type inference for parsed JSON values, string interpolation for display text, and computed properties for formatted values. These Swift basics appear on nearly every line of production code.
Learning Path
flowchart LR A[Installation] --> B[Swift Basics\nYou are here] B --> C[Collections] style B fill:#f90,color:#fff
Variables and Constants
Use var for values that change and let for values that never change:
import Foundation
// Variable - value can change
var score = 100
score += 50
print("Score: \(score)")
// Constant - value cannot change
let maxScore = 1000
// maxScore = 500 // Compile error: cannot assign to 'let' constant
// Multiple declarations on one line
var x = 0.0, y = 0.0, z = 0.0
print("x: \(x), y: \(y), z: \(z)")
Output:
Score: 150
x: 0.0, y: 0.0, z: 0.0
Type Inference and Annotations
Swift infers type from the initial value, or you can specify it explicitly:
import Foundation
// Type inference
let name = "Alice" // String
let age = 30 // Int
let height = 1.75 // Double
let isActive = true // Bool
// Explicit type annotation
let email: String = "alice@example.com"
let count: Int = 42
let pi: Double = 3.14159
let isComplete: Bool = false
print("\(name) is \(age) years old, height: \(height)m")
print("Email: \(email), Count: \(count), Pi: \(pi), Complete: \(isComplete)")
Output:
Alice is 30 years old, height: 1.75m
Email: alice@example.com, Count: 42, Pi: 3.14159, Complete: false
Data Types
Swift provides several basic data types:
import Foundation
// Integer types with different bit sizes
let small: Int8 = 127 // -128 to 127
let medium: Int16 = 32767 // -32768 to 32767
let large: Int32 = 2147483647 // -2^31 to 2^31-1
let huge: Int64 = 9223372036854775807
let unsigned: UInt = 4294967295
// Floating point
let floatValue: Float = 3.14159265 // ~6 decimal digits
let doubleValue: Double = 3.141592653589793 // ~15 decimal digits
print("Float: \(floatValue)")
print("Double: \(doubleValue)")
// String operations
let greeting = "Hello"
let name = "Swift"
let combined = greeting + ", " + name + "!"
print(combined)
print("Character count: \(combined.count)")
print("Uppercased: \(combined.uppercased())")
// Boolean
let isSwift = true
let isRust = false
print("Swift: \(isSwift), Rust: \(isRust)")
Output:
Float: 3.1415925
Double: 3.141592653589793
Hello, Swift!
Character count: 13
Uppercased: HELLO, SWIFT!
Swift: true, Rust: false
String Interpolation
Embed values in strings using \(value):
import Foundation
let product = "MacBook Pro"
let price = 2499.99
let quantity = 3
let total = price * Double(quantity)
let orderSummary = """
Order Summary:
Product: \(product)
Unit Price: $\(String(format: "%.2f", price))
Quantity: \(quantity)
Total: $\(String(format: "%.2f", total))
"""
print(orderSummary)
Output:
Order Summary:
Product: MacBook Pro
Unit Price: $2499.99
Quantity: 3
Total: $7499.97
Operators
Swift supports standard operators plus some unique ones:
import Foundation
// Arithmetic
let a = 10
let b = 3
print("a + b = \(a + b)")
print("a - b = \(a - b)")
print("a * b = \(a * b)")
print("a / b = \(a / b)")
print("a % b = \(a % b)")
// Compound assignment
var total = 100
total += 20
total -= 10
total *= 2
total /= 5
print("Compound result: \(total)")
// Comparison
print("a == b: \(a == b)")
print("a != b: \(a != b)")
print("a > b: \(a > b)")
print("a < b: \(a < b)")
// Range operators
let range = 1...5 // Closed range: 1, 2, 3, 4, 5
let halfRange = 1..<5 // Half-open: 1, 2, 3, 4
print("Range contains 3: \(range.contains(3))")
print("Half range contains 5: \(halfRange.contains(5))")
// Ternary operator
let score = 85
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"
print("Score: \(score), Grade: \(grade)")
Output:
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
Compound result: 44
a == b: false
a != b: true
a > b: true
a < b: false
Range contains 3: true
Half range contains 5: false
Score: 85, Grade: B
Type Conversion
Swift requires explicit conversion between numeric types:
import Foundation
let integerValue = 42
let doubleValue = 3.14
// Explicit conversion
let sum = Double(integerValue) + doubleValue
let rounded = Int(doubleValue)
print("Sum: \(sum)")
print("Rounded: \(rounded)")
// String to number conversion
let priceString = "29.99"
if let parsedPrice = Double(priceString) {
let tax = parsedPrice * 0.08
print("Price: $\(parsedPrice), Tax: $\(String(format: "%.2f", tax))")
}
// Number to string
let count = 100
let countString = String(count)
print("Count as string: \"\(countString)\"")
Output:
Sum: 45.14
Rounded: 3
Price: $29.99, Tax: $2.40
Count as string: "100"
Common Mistakes
- Using var when let is appropriate: If a value never changes after initialization, use let. The compiler optimizes constants better and prevents accidental modification.
- Mixing types in expressions: Swift does not implicitly convert types.
let x: Int = 3.5is an error. Use explicit initializers. - Forgetting that String is a value type: Strings in Swift are copied when assigned. Modifying one string does not affect others referencing the same value.
- Integer division truncation:
10 / 3evaluates to 3, not 3.333. Use Double for floating-point division. - Overflow in silent arithmetic: Swift traps integer overflow by default. Use
&+,&-,&*for wrapping arithmetic.
Practice Questions
What is the difference between
letandvar?letcreates an immutable constant.varcreates a mutable variable. Useletwhen the value will not change.
How does type inference work in Swift?
- The compiler examines the initial value to determine the type.
let x = 42infers Int.let y = 3.14infers Double.
- The compiler examines the initial value to determine the type.
What is string interpolation syntax?
\(expression)inside a string literal. Swift evaluates the expression and converts it to a string.
How do you convert an Int to a Double?
- Use the initializer:
Double(intValue). Both types must be explicit.
- Use the initializer:
Challenge: Write a Swift program that calculates the area and circumference of a circle. Use let for pi (3.14159), declare the radius as a variable, and print the results formatted to two decimal places.
Mini Project
Create a tip calculator:
- Declare constants for the bill amount (Double) and tip percentage (Int).
- Calculate the tip amount and total bill.
- Handle splitting the bill among any number of people.
- Use String(format:) for currency formatting.
- Print a formatted receipt showing the original bill, tip, total, and per-person amount.
FAQ
{{< faq "How do I write multi-line strings in Swift?" "Use triple quotes: \"\"\" ... \"\"\". Indentation is trimmed relative to the closing quotes." >}}What's Next
Learn how to work with groups of data in the Collections tutorial.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro