Section 5/181 menit

5. Conditional Dependencies & Platform-Specific Targets

5. Conditional Dependencies & Platform-Specific Targets

Platform Conditions

swift
// Package.swift — conditional dependencies per platform
let package = Package(
    name: "CrossPlatformApp",
    platforms: [
        .iOS(.v16),
        .macOS(.v13),
        .tvOS(.v16),
        .watchOS(.v9),
        .visionOS(.v1)
    ],
    targets: [
        .target(
            name: "AppCore",
            dependencies: [
                // Dependency tanpa kondisi — semua platform
                "Logging",
                
                // Dependency hanya untuk platform tertentu
                .product(name: "UIComponents", package: "UIKit-Components",
                         condition: .when(platforms: [.iOS, .tvOS, .visionOS])),
                
                .product(name: "AppKitComponents", package: "AppKit-Components",
                         condition: .when(platforms: [.macOS])),
                
                .product(name: "WatchComponents", package: "Watch-Components",
                         condition: .when(platforms: [.watchOS]))
            ]
        ),
        
        // Target platform-spesifik penuh
        .target(
            name: "iOSExtensions",
            dependencies: ["AppCore"],
            exclude: [],
            sources: ["Sources/iOS/"],
            publicHeadersPath: nil
        )
    ]
)

Conditional Source Files dalam Kode

swift
// Menggunakan #if os() untuk conditional compilation
#if os(iOS) || os(tvOS)
import UIKit
typealias PlatformView = UIView
typealias PlatformColor = UIColor
#elseif os(macOS)
import AppKit
typealias PlatformView = NSView
typealias PlatformColor = NSColor
#elseif os(watchOS)
import WatchKit
typealias PlatformView = WKInterfaceObject
#endif

// Cross-platform color abstraction
public struct AppColor {
    public static var primary: PlatformColor {
        #if os(macOS)
        return .systemBlue
        #else
        return .systemBlue
        #endif
    }
}