Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 146 ยท Platforms and Ecosystem

Swift on Apple Platforms

A tour of building apps in Swift for iPhone, iPad, Mac, Watch, TV and Vision Pro: Xcode, SwiftUI, UIKit and AppKit, portable code, conditional compilation, shipping.

Swift was created at Apple in 2014 to replace Objective-C as the language for iPhone, iPad and Mac apps, and Apple platforms are still where most Swift code is written. Every Apple device you can buy runs Swift: iOS and iPadOS, macOS, watchOS, tvOS and visionOS. The operating systems themselves, and many of their frameworks, are increasingly written in Swift too.

This lesson is a map. You will see what an Apple developer's world is made of (Xcode, the SDKs, the UI frameworks, the App Store), and, more importantly for this tutorial, which parts of your Swift knowledge carry over unchanged and which parts are Apple-only. Almost everything you learned in the previous lessons (structs, enums, protocols, generics, concurrency, error handling) is the same language on every platform. What changes is the framework you import.

The site's runner is Swift on Linux. It has no Apple frameworks, no Xcode and no simulator, so the Apple-specific code in this lesson is read-only and clearly labelled. The runnable examples show the parts that really are portable, and how to write code that works on both sides.

The layers

Think of an Apple app as a stack. The lower layers are the same everywhere; the upper layers are platform specific:

  1. The Swift language and standard library. Identical on all platforms: Array, String, Optional, concurrency, macros.
  2. Foundation and other portable libraries. Dates, JSON, URLs, files, Dispatch, Observation, Synchronization, Testing. Foundation exists on Linux and Windows too (see Foundation dates and JSON).
  3. System frameworks. Apple-only: networking and storage (URLSession exists elsewhere, but CloudKit, SwiftData, Core Data, HealthKit), media (AVFoundation, Core Image, Metal), machine learning (Core ML, Vision), location, notifications, payments.
  4. UI frameworks. SwiftUI (declarative, all platforms), UIKit (iOS, tvOS, visionOS), AppKit (macOS), WatchKit.
  5. Your app, built and signed by Xcode and distributed through the App Store or TestFlight.

Xcode and the toolchain

Xcode is Apple's IDE, and it only runs on macOS. It includes the Swift compiler, the SDKs for each platform, Interface Builder, simulators for every device, Instruments for profiling, the debugger, and the tooling for signing and uploading apps. A normal workflow is: create an app project, write code, run it in the simulator or on a device, profile it, and archive it for the store.

Most apps are organized as an Xcode project (the app target, with assets and settings) plus one or more Swift packages (your own reusable modules, see SwiftPM). Experienced teams keep as much code as possible in packages, for the reason in the next section.

Alternatives: Swift Playgrounds (an app for iPad and Mac for learning and small apps) and VS Code with the Swift extension. Apps for Apple devices still need Xcode's SDK to build and sign.

Know your platform

Code often has to ask "where am I running?" Swift answers at compile time with conditional compilation blocks, and at run time with availability checks:

Swift Which platform am I on?

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.

On this runner you see Linux, SwiftUI is not available here, UI framework: none and architecture: x86_64. The same file on a Mac with an Apple silicon chip prints macOS, SwiftUI is available and arm64; the UI framework line reads UI framework: AppKit. Notes:

  • #if os(...) and #if canImport(...) are decided when the code is compiled. The code in the false branches must still parse, but it is not type-checked, so it can mention types that do not exist on this platform.
  • #available(iOS 17, macOS 14, *) is decided when the app runs. If your app supports iOS 16 but wants an iOS 17 API, wrap the call in if #available and provide a fallback. The * means "any other platform".
  • Prefer canImport(UIKit) to os(iOS) when you are really asking "do I have this framework?". It also covers visionOS, tvOS and Mac Catalyst.

Your code or the framework's code?

Apple frameworks can only be imported on Apple platforms. If you try on Linux you get the real compile error:

Swift Importing an Apple-only framework (fails on purpose)

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 message is error: no such module 'UIKit'. Likewise, anything that relies on the Objective-C runtime is missing off Apple platforms:

Swift @objc outside Apple platforms (fails on purpose)

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.

You get error: Objective-C interoperability is disabled for the attribute and error: '#selector' can only be used with the Objective-C runtime for the selector. On Apple platforms both are fine, and UIKit and AppKit rely on them for target-action. SwiftUI mostly does not need them, and neither does new code that uses closures.

Put your logic where you can test it

The most useful architectural habit for an Apple developer is also the simplest: keep the code that decides things away from the code that draws things. Business rules, parsing, formatting and data models should be plain Swift that never imports UIKit or SwiftUI. Then:

  • you can unit test them in milliseconds, even on Linux in continuous integration (see Testing in Swift);
  • you can reuse them in the iOS app, the macOS app, the watch app and a server;
  • the view layer stays thin, which is the hardest layer to test.

Here is a model plus a "view model" with no UI import at all. A SwiftUI view or a UIKit view controller would only display viewModel.title and call viewModel.toggle(_:):

Swift A portable model and view model

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.

On an iPhone the data would come from SwiftData or a server; here it is a literal. The logic does not change. This split is what the architecture names MVC, MVVM and "unidirectional data flow" all describe in different words.

SwiftUI, UIKit and AppKit

You choose a UI framework per project, and often mix them:

Framework Style Platforms Today
SwiftUI Declarative: describe the UI for a state iOS, iPadOS, macOS, watchOS, tvOS, visionOS Apple's recommended default for new apps; see the SwiftUI overview
UIKit Imperative: views and view controllers you create and update iOS, iPadOS, tvOS, visionOS Mature and huge; essential for existing apps and fine control
AppKit Imperative, like UIKit macOS Used for advanced Mac apps
WatchKit Older watch UI watchOS Replaced by SwiftUI

They interoperate: UIHostingController puts a SwiftUI view inside UIKit, and UIViewRepresentable wraps a UIKit view for SwiftUI. Below is a read-only side-by-side of the same screen, only to show the difference in style:

Swift
// Read-only example: needs Xcode and SwiftUI.
import SwiftUI

struct Greeting: View {
    @State private var name = ""

    var body: some View {
        VStack {
            TextField("Your name", text: $name)
            Text("Hello, \(name)!")
        }
        .padding()
    }
}
Swift
// Read-only example: needs Xcode and UIKit.
import UIKit

final class GreetingViewController: UIViewController {
    private let field = UITextField()
    private let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        field.placeholder = "Your name"
        field.addTarget(self, action: #selector(nameChanged), for: .editingChanged)
        label.text = "Hello, !"
        // ... add both to a stack view and set constraints ...
    }

    @objc private func nameChanged() {
        label.text = "Hello, \(field.text ?? "")!"
    }
}

In SwiftUI you describe what the screen looks like for a given state and the framework updates it. In UIKit you build the views and update them yourself whenever something changes. SwiftUI code is far shorter, UIKit code gives you more control and exists in every older project.

Data, concurrency and the main actor

Two Apple-platform topics build directly on earlier lessons:

  • The main actor. UI frameworks may only be touched from the main thread. In Swift this is expressed with @MainActor: SwiftUI's View protocol is isolated to it, and view models are usually marked @MainActor. The compiler then checks, for you, that background work (a Task, an actor) hops back before touching the UI. See actors and Sendable.
  • Persistence. SwiftData (declarative models with the @Model macro, built on Swift macros, see macros), Core Data (older, still widespread), UserDefaults for small settings, the Keychain for secrets, files for the rest.

Shipping an app

A short, read-only checklist of what is different from building a command-line tool:

  • Signing. Every app is signed with a certificate tied to your Apple Developer Program membership. Xcode manages most of it ("Automatically manage signing").
  • Capabilities and entitlements. Push notifications, iCloud, HealthKit and similar features must be declared in the project and the developer portal.
  • Privacy. You describe why your app needs the camera or location (Info.plist usage strings), and declare data collection in App Store Connect.
  • TestFlight. Beta distribution to testers before release.
  • App Review. Every release is reviewed against the App Review Guidelines. Plan for rejections and read feedback closely.
  • Swift versions. A new Xcode ships each year with a new Swift. Your code compiles with the language mode you choose in the build settings, so you can adopt Swift 6 targets one at a time (see language versions).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which part of an Apple app is the same Swift on every platform?

    Structs, enums, protocols, generics, concurrency and error handling are language features. UIKit and SwiftUI are frameworks tied to Apple platforms.
  2. 2. What does #if canImport(UIKit) do?

    It is a compile-time condition. Run-time version checks are done with if #available.
  3. 3. Which error do you get from import UIKit on Linux?

    The module does not exist for that target, so the import fails at compile time.
  4. 4. Why keep business logic in plain Swift types instead of in view code?

    Separating decisions from drawing is the foundation of testable, reusable app architecture.
  5. 5. What does @MainActor express for UI code?

    UI frameworks must be used from the main thread. The main actor makes this a compile-time checked rule.

Summary

  • Swift runs on iOS, iPadOS, macOS, watchOS, tvOS and visionOS; the language is the same everywhere, the frameworks differ.
  • Xcode (macOS only) provides the compiler, SDKs, simulators, debugger, Instruments and signing; SwiftPM manages your own modules.
  • Use #if os(...) and #if canImport(...) for compile-time differences and if #available for run-time OS versions.
  • SwiftUI is the modern declarative UI framework; UIKit and AppKit are the established imperative ones, and they can be mixed.
  • Apple-only things (UIKit, @objc, selectors) fail to compile elsewhere; keep models and logic in plain Swift so they are portable and testable.
  • UI work belongs on the main actor; shipping involves signing, privacy declarations, TestFlight and App Review.

Next: SwiftUI Overview