Swift: What It Is, Syntax and Key Language Concepts

Author: IT Sectr Published: 2026-02-09 Reading time: 8 min

Swift is a modern programming language from Apple, introduced at WWDC 2014 as a replacement for Objective-C. Swift combines type safety, automatic memory management ARC (Automatic Reference Counting), and a protocol-oriented approach. Swift Programming Language is the primary source for the language's syntax and standard library.

Key Takeaways

  • Swift is a statically typed language with type inference, Optionals, and Protocol-Oriented Programming
  • Optionals — type-safe nil handling via Optional Binding (if let) and Optional Chaining (?.)
  • ARC — automatic reference counting for memory management without manual retain/release
  • Closures — anonymous functions with context capture, used in callback APIs and functional chains
  • Struct vs Class — value types vs reference types with different assignment and inheritance behavior

What is Swift?

Swift is a multi-paradigm programming language developed by Apple for iOS, macOS, watchOS, tvOS, and visionOS. The language's key goals are safety, speed, and syntactic expressiveness. Swift uses the LLVM compiler and generates optimized machine code comparable in performance to C++.

Since its release in 2014, Swift has gone through 6 major versions. Swift 6 (2024) introduced a complete data-race safety model through strict control of concurrent code isolation. According to GitHub Octoverse 2025, Swift ranks in the top 10 languages by community growth, outpacing Rust and Kotlin in adoption speed on Apple platforms.

Swift is open source and cross-platform — the source code is published on GitHub (Swift Open Source). Beyond Apple platforms, Swift is used on Linux and Windows for server-side development (Vapor, Hummingbird), though its primary domain remains mobile and desktop development within the Apple ecosystem.

Why Swift Replaced Objective-C

The main reasons for the transition: Swift eliminates entire classes of bugs possible in Objective-C. Type safety prevents type mismatches at compile time. Optionals eliminate nil dereferencing. ARC has been built in from day one, unlike MRC/ARC in Objective-C. Swift syntax is shorter and more readable — studies show a 30-40% reduction in code volume compared to Objective-C for equivalent tasks.

Syntax and Basic Constructs

The basic Swift syntax combines familiar C-like constructs with elements from functional languages. Variables are declared with var, constants with let. The compiler uses type inference, so explicit type annotation is only required in ambiguous cases.

swift
import Foundation

// Constants and variables
let name = "Swift"
var version = 6.0
var count: Int = 42

// Functions with default parameters
func greet(person: String, greeting: String = "Hello") -> String {
    return "\(greeting), \(person)!"
}

// Guard-let for early exit
func parse(input: String?) -> Int {
    guard let value = input, let number = Int(value) else {
        return 0
    }
    return number
}

Switch and pattern matching in Swift are more powerful than in C and Kotlin. Switch supports matching with tuples, ranges, where conditions, and value binding. The compiler checks exhaustive coverage of all cases — omitting default is not an error if all possible values are covered.

swift
let point = (x: 3, y: -1)

switch point {
case (0, 0):
    print("Origin")
case let (x, y) where x == y:
    print("X equals Y")
case let (x, y) where abs(y) > x:
    print("Absolute value of Y is greater than X")
default:
    print("Point \("point.x), \(point.y))")
}

Optionals and Safe nil Handling

Optionals are a core concept in Swift that solves the null reference problem at the type system level. Optional is an enum with two cases: .none (nil) and .some(Wrapped). The compiler forbids using an Optional without explicit unwrapping, eliminating an entire class of runtime errors.

swift
var optionalString: String? = "Hello"
optionalString = nil  // allowed

// Optional Binding — safe unwrapping
if let text = optionalString {
    print("Text: \("text)")
} else {
    print("Value absent")
}

// Optional Chaining — safe property access
let length = optionalString?.count ?? 0

// Nil-coalescing operator
let greeting = optionalString ?? "Default"

Optional Chaining with the ?. operator allows safely calling methods and accessing properties of an optional value. If the chain encounters nil, the entire expression evaluates to nil. Nil-coalescing (??) provides a default value and is widely used in UI code for displaying placeholder text.

Protocols and Extensions

Protocols in Swift define a contract — a set of properties and methods. Unlike Java interfaces, Swift protocols can have default implementations via protocol extensions. This is the foundation of Protocol-Oriented Programming, Apple's recommended approach over class inheritance.

swift
protocol NamedEntity {
    var name: String { get }
    func description() -> String
}

// Default implementation via extension
extension NamedEntity {
    func description() -> String {
        return "Entity: \(name)"
    }
}

// Conformance via extension
extension String: NamedEntity {
    var name: String { return self }
}

Protocol Extensions allow adding methods to a protocol without modifying each conforming type. This is especially useful for adding common utilities: map, filter, reduce for Sequence, or Codable for JSON serialization. Apple built many frameworks (SwiftUI, Combine) on protocols with extensions.

Closures and Functional Chains

Closures in Swift are anonymous functions that capture variables from their surrounding context. Syntactically, closures resemble lambdas in Kotlin but with a more flexible syntax: trailing closure, shorthand argument names ($0, $1), and autoclosures.

swift
// Closure with context capture
let numbers = [5, 3, 8, 1, 9]

// Trailing closure syntax
let sorted = numbers.sorted { $0 < $1 }

// Functional chain
let result = numbers
    .filter { $0 > 3 }
    .map { $0 * 2 }
    .reduce(0, +)

// Closure as function parameter
func performAsync(completion: @escaping (Result<Data, Error>) -> Void) { }

@escaping closures are used when the closure executes after the function returns — typical for network requests and asynchronous operations. @autoclosure automatically wraps an expression into a closure, used in assert and short-circuit logic.

Structures and Classes: Comparison

The choice between struct and class is one of the first decisions when designing a Swift model. Apple recommends using struct by default (value type) and switching to class (reference type) only when inheritance or reference identity is needed.

CharacteristicStructClass
Passing typeBy value (copy)By reference
InheritanceNot supportedSupported
ARC managementNot requiredARC (reference counting)
Deinitializer deinitNoYes
Mutabilitymutating func to modify propertiesAny method can mutate
Storage in collectionsCopied on insertionReference stored

Value types (struct) are safer in multithreaded environments — each thread gets an independent copy. Reference types (class) are necessary for working with UIKit (UIView, UIViewController), where reference identity and inheritance from system classes are required.

ARC Memory Management

ARC (Automatic Reference Counting) is Swift's memory management system for reference types. The compiler inserts retain/release calls at runtime, tracking the number of strong references to an object. When the counter reaches zero, the object is immediately deallocated.

The main problem with ARC is retain cycles. When two objects hold strong references to each other, memory is never freed. The solution is weak references (automatically become nil upon deallocation) and unowned references (guaranteeing the object is alive).

swift
class ProfileViewController: UIViewController {
    var onLogout: (() -> Void)?
    
    func setupHandler() {
        // [weak self] prevents retain cycle
        onLogout = { [weak self] in
            guard let self else { return }
            self.dismiss(animated: true)
        }
    }
}

To prevent retain cycles in closures, use [weak self] with guard let self = self else { return }. This rule is especially important in UIKit, where ViewController holds strong references to its properties, and closures inside those properties reference the ViewController.

Frequently Asked Questions

What data types are available in Swift?

Swift supports Int, Double, Float, String, Bool, Array, Set, Dictionary, and tuples. Numeric types have fixed sizes: Int8, Int16, Int32, Int64, and unsigned UInt. For working with dates, Date from Foundation is used; for data, Data.

What is an Optional in Swift and why is it needed?

Optional is an enum with two cases: .none (nil) and .some(Wrapped). Swift requires explicit Optional unwrapping via if let, guard let, or ??, which eliminates NullPointerException. Optional chaining (?.) allows safe access to properties of nested optional values.

How is struct different from class in Swift?

Struct — a value type, copied on assignment, does not support inheritance, does not require ARC. Class — a reference type, passed by reference, supports inheritance and deinitializers. Apple recommends struct as the default type.

How does ARC memory management work in Swift?

ARC automatically counts strong references to class objects. When the count reaches zero, memory is freed. To prevent retain cycles, use weak (automatic nil) and unowned (guaranteed lifetime). ARC does not apply to struct and enum.

What is Protocol Oriented Programming in Swift?

Protocol-Oriented Programming is an approach that uses protocols with extensions instead of class hierarchies. Protocols can contain default method implementations via protocol extensions. This allows code reuse without inheritance, maintaining flexibility and testability.

Summary

  • Swift — Apple's statically typed language with Optionals, ARC, and Protocol-Oriented Programming for iOS/macOS development
  • Optionals — type-safe nil handling via Optional Binding, Optional Chaining, and nil-coalescing operator
  • Protocols + Extensions — the foundation of Protocol-Oriented Programming with default method implementations and composition
  • Closures — anonymous functions with context capture, trailing syntax, and capture lists for memory management
  • Struct vs Class — value types (copying, thread safety) versus reference types (inheritance, ARC)
  • ARC — automatic reference counting with weak/unowned modifiers to prevent retain cycles
  • Switch and pattern matching — exhaustive coverage, tuple matching, ranges, and where conditions

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also