Skip to content

Swift Basics

Swift’s syntax is designed for readability, safety, and expressiveness. This document covers foundational elements: syntax, comments, semicolons, operators, and basic program structure.

Program Structure

Swift programs are organized into modules (e.g., apps, frameworks) and consist of top-level declarations (variables, functions, types). Files use the .swift extension, and no main function is required for executables.

Example: Simple Program:

swift
import Foundation // Import standard library
let greeting = "Welcome to Swift!"
print(greeting)

Comments

Comments document code and improve maintainability.

  • Single-line: // for inline notes.
  • Multi-line: /* */ for blocks.
  • Documentation: /// or /** */ for API docs, supporting Markdown.

Example:

swift
// Calculate area of a rectangle
func area(width: Double, height: Double) -> Double {
    /* Ensure positive dimensions */
    return max(0, width) * max(0, height)
}

/// Computes the area of a rectangle.
/// - Parameters:
///   - width: The rectangle's width.
///   - height: The rectangle's height.
/// - Returns: The area as a `Double`.
func documentedArea(width: Double, height: Double) -> Double {
    return width * height
}

Generating Documentation:

Use xcodebuild docbuild or tools like Jazzy to create HTML documentation from doc comments.

Semicolons

Semicolons (;) are optional in Swift, except when multiple statements appear on the same line.

Example:

swift
let x = 10; print(x) // Semicolon required
let y = 20
print(y) // No semicolon

Basic Operators

Swift supports standard operators for arithmetic, comparison, and logic.

Arithmetic Operators

  • +, -, *, /, % (remainder).
  • Compound assignments: +=, -=, etc.

Example:

swift
let sum = 5 + 3 // 8
let remainder = 10 % 3 // 1
var count = 5
count += 2 // 7

Comparison Operators

  • ==, !=, >, <, >=, <=.

Example:

swift
let isEqual = (5 == 5) // true
let isGreater = (10 > 5) // true

Logical Operators

  • && (and), || (or), ! (not).

Example:

swift
let hasAccess = true && false // false
let isValid = !hasAccess // true

Range Operators

  • Closed: a...b (includes a and b).
  • Half-open: a..<b (excludes b).
  • One-sided: a..., ...b.

Example:

swift
for i in 1...5 {
    print(i) // 1, 2, 3, 4, 5
}
for j in 1..<3 {
    print(j) // 1, 2
}
let highScores = [100, 90, 80]
for score in highScores[1...] {
    print(score) // 90, 80
}

Operator Precedence

Swift follows standard precedence rules (e.g., * before +). Use parentheses for clarity.

Example:

swift
let result = 2 + 3 * 4 // 14 (3 * 4 = 12, then 2 + 12)
let explicit = (2 + 3) * 4 // 20

Modules and Imports

Modules encapsulate code. Import modules with import.

Example:

swift
import UIKit // Import UIKit for iOS
import Foundation // Import core utilities

Attributes

Attributes (e.g., @available, @discardableResult) modify declarations.

Example:

swift
@available(iOS 13, *)
func modernFeature() {
    print("iOS 13+ only")
}

@discardableResult
func calculate() -> Int {
    return 42
}
calculate() // No warning for unused result

Best Practices

  • Use descriptive names for variables and functions.
  • Omit semicolons unless required.
  • Write clear documentation comments for public APIs.
  • Use consistent indentation (4 spaces recommended).
  • Import only necessary modules to reduce build times.
  • Follow Swift API Design Guidelines for naming.

Troubleshooting

  • Syntax Errors: Check for mismatched parentheses or missing keywords.
  • Module Not Found: Ensure the module is included in the target or SPM dependencies.
  • Ambiguous Operators: Use parentheses to resolve precedence issues.
  • Deprecated APIs: Check @available annotations for platform compatibility.

Released under the MIT License.