Section 9/171 menit

9. Local Package & Modular Architecture

9. Local Package & Modular Architecture

Local package adalah cara paling powerful menggunakan SPM untuk app modularization.

Pattern: App Shell + Feature Packages

swift
MyApp.xcworkspace/
├── MyApp.xcodeproj                 # Thin app shell (entry point + DI)
└── Modules/
    ├── CoreUI/                     # Shared design system
    │   ├── Package.swift
    │   └── Sources/CoreUI/
    ├── Networking/                 # API client
    │   ├── Package.swift
    │   └── Sources/Networking/
    ├── LoginFeature/               # Self-contained feature
    │   ├── Package.swift
    │   └── Sources/LoginFeature/
    └── HomeFeature/
        ├── Package.swift
        └── Sources/HomeFeature/

App shell tinggal depend ke feature package via Package(path:):

Di Xcode: File → Add Package Dependencies → Add Local → pilih folder Modules/LoginFeature.

Manfaat

Manfaat Penjelasan
Build speed Module yang tidak berubah pakai cache. Recompile incremental.
Boundaries Cross-feature import harus eksplisit via Package.swift — mencegah accidental coupling.
Preview & playground Setiap module bisa di-preview SwiftUI atau di-run swift run independen.
Parallel work Team A kerja di LoginFeature, Team B di HomeFeature — minim merge conflict.
Testability Test target per module, tidak perlu compile seluruh app.

Aturan Praktis Modular SPM

  1. Tidak ada cyclic dependency. Feature A tidak boleh depend ke Feature B yang depend balik ke A.
  2. Feature → Core, tidak sebaliknya. Core module (UI, networking) tidak tahu feature.
  3. Komunikasi antar feature via app shell. App shell yang compose, bukan feature memanggil feature lain langsung.
  4. package access level untuk shared internal. Sejak Swift 5.9, gunakan package untuk symbol yang shared antar module tapi bukan public API.
swift
// Di module CoreNetworking
package final class HTTPClient {
    package func request(_ url: URL) async throws -> Data { /* ... */ }
}
// Bisa diakses LoginFeature, HomeFeature, tapi tidak oleh user library