Jump to content
Syntax Sample (Swift)

Types, protocols and enums with associated values.

import Foundation

/// A window as the desktop tracks it.
public struct Window: Identifiable, Sendable {
  public let id: UUID
  public var title: String
  public var frame: CGRect
  public var isZoomed: Bool = false

  static let minimumSize = CGSize(width: 320, height: 240)
}

enum LoadState<Value> {
  case idle
  case loading(progress: Double)
  case loaded(Value)
  case failed(any Error)
}

protocol WindowManaging: AnyObject {
  var windows: [Window] { get }
  func bringToFront(_ id: UUID) throws
}

Control flow, optionals and string interpolation.

extension WindowManaging {
  func summary(for id: UUID) -> String {
    guard let window = windows.first(where: { $0.id == id }) else {
      return "No window with id \(id)."
    }

    let size = window.frame.size
    let label = window.title.isEmpty ? "Untitled" : window.title

    switch (window.isZoomed, size.width) {
    case (true, _):
      return "\(label) is zoomed."
    case (false, let width) where width < Window.minimumSize.width:
      return "\(label) is only \(Int(width))pt wide."
    default:
      return String(format: "%@ — %.0f×%.0f", label, size.width, size.height)
    }
  }
}

@MainActor
final class Desktop: WindowManaging {
  private(set) var windows: [Window] = []

  func bringToFront(_ id: UUID) throws {
    guard let index = windows.firstIndex(where: { $0.id == id }) else {
      throw CocoaError(.fileNoSuchFile)
    }

    let window = windows.remove(at: index)
    windows.append(window)
  }
}