Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 146 ยท Practice

Swift for Developers from Other Languages

A practical guide to Swift for developers who already know Java, Kotlin, C#, Python or JavaScript - concept map, key differences in nullability, value types, errors and concurrency, with runnable code.

If you already program in another language, you do not need to relearn what a loop is. You need a map: which of your habits carry over, which do not, and where Swift quietly behaves differently from what you expect. This lesson is that map. It compares Swift with Java, Kotlin, C#, Python and JavaScript, and every claim about Swift comes with code you can run.

Swift sits in an unusual spot. Its syntax and ideas will feel familiar to Kotlin and C# developers, its type system is closer to Rust than to Java in places, and its feel for readable call sites is all its own. Three differences matter more than the rest: Swift's value types (structs and enums) do much of the work that classes do elsewhere, it has no null (optionals are a real type), and its memory management is deterministic reference counting rather than a garbage collector. Keep those three in mind as you read.

The concept map

Concept Java Kotlin C# Python JavaScript Swift
Constant / variable final / plain val / var readonly, const / plain convention only const / let let / var
Missing value null, Optional T? T? None null, undefined Optional<T> (T?)
Data holder record data class record @dataclass object literal struct
Interface interface interface interface Protocol or ABC duck typing protocol
Sum type sealed + records sealed class records + patterns unions, match tagged objects enum with associated values
Add methods to a type not possible extension function extension method monkey-patching prototype extension
Asynchrony CompletableFuture, virtual threads coroutines Task, async/await asyncio Promise, async/await async/await, tasks, actors
Cleanup try-with-resources use using with finally defer, deinit
Memory GC GC GC refcount + cycle GC GC ARC (reference counting)
Generics erased erased (reified inline) reified dynamic dynamic specialized at compile time
Strings index by UTF-16 unit UTF-16 unit UTF-16 unit code point UTF-16 unit grapheme cluster (String.Index)

Programs start at the top of main.swift as in a script (no class Main needed), or at an @main type in larger projects.

No null: optionals are a type

In Java, C# before nullable reference types, Python and JavaScript, any reference may be null, and the compiler cannot tell you which. Kotlin and modern C# added T? annotations. Swift went further: Int? is a different type from Int, a wrapper (Optional<Int>) that is either a value or nil. You cannot use it as an Int until you unwrap it, and the compiler checks every use, for value types as well as classes.

Swift Optionals instead of null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Compared with each language:

  • Java: Optional<T> exists but is optional itself and boxed; Swift's version is how all absent values work, with first-class syntax (?, ?., ??, if let).
  • Kotlin and C#: the closest match. The difference is mostly that Swift's optionals are real wrapper values, so Int?? exists and map/flatMap work on them.
  • Python and JavaScript: None, null and undefined collapse into one nil, and nothing is "falsy". Conditions must be Bool: if count { } does not compile, so write if count > 0.

Value types do the heavy lifting

In Java, C#, Python and JavaScript, objects are references: assigning one to a new variable gives you two names for the same object, and passing it to a function lets the function change it. Swift's structs, enums, arrays, dictionaries, sets and strings are values: assignment copies (with copy-on-write, so copies are cheap until you change one). This removes a whole category of aliasing bugs.

Swift Copies instead of aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The consequence for design: in Swift you reach for a struct first, as you would for a Java record or C# record struct, and use a class only when you want shared identity, inheritance from a framework class, or a lifetime you control with deinit. Standard types such as String, Array and Date are structs, which is why Swift code needs fewer defensive copies than Java code.

Types: structs, enums and protocols

Swift's enums are what Java developers know as sealed hierarchies with records, and Kotlin developers as sealed classes: each case can carry its own data, and switch must cover every case. Protocols play the role of interfaces, but they can also be adopted by structs and enums, and an extension can give every conforming type a default implementation (as Java's default methods and C#'s default interface members do, but more widely used).

Swift Enums with data, protocols and extensions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Other type-system differences that surprise people:

  • Argument labels are part of the name. move(from: a, to: b) is move(from:to:). Labels read like English at the call site and replace what you would do with builder objects or named arguments in other languages.
  • Classes are not final by default, unlike Kotlin. Mark them final when you do not intend subclasses; Swift can then optimize calls.
  • No checked exceptions, no unchecked ones. See the next section.
  • Generics are specialized, not erased. A generic function over Int can compile to the same machine code as a hand-written Int function.
  • Access control has private, fileprivate, internal (default), package, public and open. The default is the module, not the package/namespace.

Errors are values you must acknowledge

Swift has throw, try and catch, but errors are not exceptions that unwind through frames unnoticed. A function that can fail says so with throws, and every call to it is marked with try, similar to Java's checked exceptions without the type list, or like Rust's ? operator. Swift 6 also lets you declare the exact error type (throws(ParseError)). There is no finally; defer runs a block when the scope ends, and deinit cleans up objects.

Swift try, catch, defer and Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Programming mistakes are handled differently from errors: an index out of range, integer overflow or a force-unwrapped nil stops the program. Swift treats those as bugs, not as recoverable conditions, and does not let you catch them. If you come from Python or JavaScript, where almost anything can be caught, the discipline is: use throws for failures the caller could reasonably handle (bad input, missing file, no network) and let bugs crash.

Familiar arithmetic and strings, with different rules

Developers from Python, JavaScript and Java are most often surprised by small numeric and string details. Two things to learn: integer arithmetic traps on overflow instead of wrapping (Java, C#) or growing without bound (Python), and strings are sequences of user-perceived characters, not of code units or code points.

Swift Numbers and strings that behave differently

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two more habits to adjust. Swift has no truthiness at all, so if let and explicit comparisons replace if x: and if (x). And == on strings and collections compares values, not identity, while === compares class instances by identity.

Closures and collection pipelines

Swift's closure syntax resembles Kotlin's lambdas, with $0, $1 where Kotlin has it. The standard-library methods map, filter, reduce, compactMap, flatMap, sorted and contains(where:) cover what Java streams, LINQ and Python comprehensions do, but they run eagerly on arrays unless you add .lazy.

Swift Pipelines: streams, LINQ and comprehensions in Swift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Concurrency: async/await with structure

If you know JavaScript promises or C# Task, Swift's async/await will look familiar, with one significant difference: Swift concurrency is structured. Child tasks belong to their parent; leaving a scope waits for them or cancels them; cancellation flows down; and shared mutable state lives in actors, which the compiler checks. There is no fire-and-forget by default. A Swift 6 build will refuse to compile many classic data races.

Swift Promise.all, Task.WhenAll and actors in Swift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Where a Java developer reaches for synchronized or an AtomicInteger, and a JavaScript developer never worries because the event loop is single threaded, a Swift developer uses an actor (or a Mutex for tiny critical sections). See Swift concurrency and actors.

Memory: ARC, not a garbage collector

Swift counts references to class instances. When the count drops to zero the object is destroyed immediately and deinit runs, so cleanup is deterministic, as in C++ RAII or Rust drops, and not "some time later" as with a GC. The cost is that reference cycles are never collected, which you break with weak and unowned references. Value types need no counting at all. Read memory management with ARC once you have used classes.

Language-by-language cheat notes

Coming from Java. Think "Kotlin-like Java with value types and no null". Replace getters and setters with properties, builders with argument labels and defaults, Optional chains with ?., visitor patterns with enums and switch, and interface plus abstract class with protocols and extensions. There is no checked-exception list, no static nested class pain, and no boxed Integer. Compare Java records with Swift structs.

Coming from Kotlin. Almost everything transfers: val/var become let/var, ?: becomes ??, when becomes switch, data class becomes struct, sealed classes become enums, extension functions become extensions, and coroutines become tasks. Differences: classes are not final by default, labels are mandatory unless you write _, there is no object keyword (use a static let or a struct), and the standard library is smaller; Foundation fills some gaps. See the Kotlin null safety lesson for the closest comparison.

Coming from C#. Properties, async/await, generics, LINQ-style pipelines and pattern matching will feel at home. Differences: no garbage collector, structs are the default choice, enums are far more powerful, using becomes defer and deinit, and nullability is a real wrapper type. See C# records and nullable reference types.

Coming from Python. Swift is statically typed, compiled, and uses braces instead of indentation. You gain compile-time checks and speed; you lose duck typing, the REPL-first workflow and unlimited integers. Replace list comprehensions with map/filter, None with nil, dataclass with struct, with with defer, and dict with Dictionary (unordered!). Your Python type hints map closely onto Swift types; see Python type hints for the Python side.

Coming from JavaScript. Expect the compiler to reject much of what JavaScript tolerates: no any by default, no truthiness, no implicit conversions, no undefined. const and let become let and var, template strings become interpolation, destructuring becomes tuple and pattern matching, and promises become async/await with structured tasks. See JavaScript closures for how Swift's capture rules compare.

What not to carry over

  • Do not wrap everything in classes. A struct is the default; promote to a class only for a reason.
  • Do not force-unwrap to "make it compile". Each ! is a possible crash.
  • Do not use exceptions for control flow. Return an optional or a Result, or throw only real failures.
  • Do not fight argument labels. Name functions so that the call reads as a sentence.
  • Do not expect dictionary or set order. It differs between runs.
  • Do not ignore compiler warnings about unused results and unreachable code. They are usually right.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Swift represent a value that might be missing?

    Optionals are an ordinary generic enum in the standard library, with syntax support. The compiler forces you to deal with nil before using the value.
  2. 2. What happens after var b = a when a is an array and you append to b?

    Swift arrays, dictionaries, strings and structs have value semantics. Python lists and Java arrays are references.
  3. 3. Which Swift feature plays the role of Java's try-with-resources and Python's with?

    defer runs a block when the current scope exits, however it exits; deinit runs when an object's last reference goes away.
  4. 4. What does -7 / 2 evaluate to in Swift?

    Swift follows C, Java and C#: integer division truncates toward zero, and the remainder -7 % 2 is -1.
  5. 5. How is Swift's structured concurrency different from JavaScript promises?

    A task group or async let cannot outlive its scope. This avoids orphaned work, and actors let the compiler check shared state.

Summary

  • Swift has no null: absence is Optional<T>, and the compiler makes you handle it.
  • Structs, enums, arrays, dictionaries and strings are values; classes are references. Default to structs.
  • Enums with associated values replace sealed hierarchies; protocols and extensions replace interfaces, default methods and extension functions.
  • Errors use throws/try/catch, Result and defer; programming bugs trap and cannot be caught.
  • Integer division truncates toward zero, integers do not grow or wrap silently, and strings count grapheme clusters.
  • Concurrency is structured (async let, task groups, cancellation) with actors guarding state; memory is managed by ARC rather than a garbage collector.

Next: Swift Interview Questions