### Install LLDB Plugin Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_debug/SKILL.md Run this command once per environment to install the LLDB plugin and configure `~/.lldbinit`. ```bash scripts/swift_debug install ``` -------------------------------- ### Test Lifecycle with Setup and Teardown (Instance) Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/test_basics.md Define setup and teardown logic for each test within a suite using `init()` and `deinit()`. This is useful for managing resources per test. ```swift @Suite struct DatabaseTests { var database: Database! init() { // Runs before each test database = Database.inMemory() } deinit { // Runs after each test database.close() } @Test func insert() { database.insert(item) #expect(database.count == 1) } } ``` -------------------------------- ### Multi-Target Package Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md An example of a package with multiple targets and products, demonstrating dependency management and inter-target relationships. ```swift let package = Package( name: "NetworkingKit", platforms: [.iOS(.v15), .macOS(.v12)], products: [ .library(name: "Networking", targets: ["Networking"]), .library(name: "Auth", targets: ["Auth"]), .library(name: "NetworkingAll", targets: ["Networking", "Auth"]), ], dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.8.0"), ], targets: [ .target( name: "Networking", dependencies: [ .product(name: "Alamofire", package: "Alamofire"), ] ), .target( name: "Auth", dependencies: ["Networking"] ), .testTarget( name: "NetworkingTests", dependencies: ["Networking"] ), ] ) ``` -------------------------------- ### Implement Shared Setup and Teardown for Suites Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/organization.md Use static `setUp()` and `tearDown()` methods within a `@Suite` to perform actions before and after all tests in the suite run, such as initializing or cleaning up resources. ```swift @Suite struct DatabaseTests { static var sharedDatabase: Database! static func setUp() { sharedDatabase = Database.inMemory() } static func tearDown() { sharedDatabase.close() } var database: Database { Self.sharedDatabase } } ``` -------------------------------- ### Basic Swift Test Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/SKILL.md Demonstrates a basic test function for addition and a test that expects an error to be thrown. Ensure the 'Testing' module is imported. ```swift import Testing @Test func addition() { let result = 1 + 1 #expect(result == 2) } @Test func throwsError() throws { #expect(throws: MyError.invalid) { try riskyOperation() } } ``` -------------------------------- ### Accessing Package Resources in Code Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Provides an example of how to access resources bundled within a Swift package module at runtime. ```swift // In code if let url = Bundle.module.url(forResource: "data", withExtension: "json") { let data = try Data(contentsOf: url) } ``` -------------------------------- ### Install SwiftZilla Skill using skills.sh Source: https://github.com/swiftzilla/skills/blob/main/README.md Use this command to add the SwiftZilla skill to your agent environment if it supports the `skills.sh` CLI format. Adjust the repository path as needed. ```bash npx skills add SwiftZilla-org/skills/skills/swiftzilla ``` -------------------------------- ### Class (Reference Type) Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/types.md Demonstrates a class as a reference type. Assigning a class instance to a new variable copies the reference, leading to shared state. ```swift class Person { var name: String weak var friend: Person? // Weak reference to avoid cycles init(name: String) { self.name = name } } let alice = Person(name: "Alice") let bob = alice // bob refers to the SAME instance bob.name = "Bob" // Mutates the shared instance print(alice.name) // "Bob" ``` -------------------------------- ### Swift Test Suite Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/SKILL.md Demonstrates how to organize related tests into a suite using the '@Suite' attribute. This helps in grouping tests for a specific component or feature, like a Calculator. ```swift @Suite struct CalculatorTests { let calculator = Calculator() @Test func add() { #expect(calculator.add(2, 3) == 5) } @Test func subtract() { #expect(calculator.subtract(5, 3) == 2) } } ``` -------------------------------- ### DocC Comment Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Document your public API using DocC comments in Swift code. Includes examples of usage within the documentation. ```swift /// A network manager for API requests /// /// Use `NetworkManager` to make HTTP requests: /// /// ```swift /// let manager = NetworkManager() /// let data = try await manager.fetch(url) /// ``` public class NetworkManager { // ... } ``` -------------------------------- ### Async Swift Test Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/SKILL.md Shows how to write an asynchronous test function using 'async throws'. This is useful for testing operations that involve network requests or other asynchronous operations. ```swift @Test func fetchData() async throws { let data = try await fetchUser() #expect(data.name == "Ada") } ``` -------------------------------- ### Async/Await Data Fetching Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/SKILL.md A basic example of an asynchronous function using async/await to fetch data from a URL. It throws an error if the operation fails. ```swift func fetchData() async throws -> Data { let (data, _) = try await URLSession.shared.data(from: url) return data } ``` -------------------------------- ### Complete MVVM Example with Combine Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/integration.md A full implementation of the Model-View-ViewModel (MVVM) pattern using Combine for asynchronous data fetching and state management. Includes a service layer, view model, and SwiftUI view. ```swift // Model struct User: Codable { let id: Int let name: String } // ViewModel class UserListViewModel: ObservableObject { @Published var users = [User]() @Published var isLoading = false @Published var errorMessage: String? private var cancellables = Set() private let apiService: APIServiceProtocol init(apiService: APIServiceProtocol = APIService()) { self.apiService = apiService } func fetchUsers() { isLoading = true errorMessage = nil apiService.fetchUsers() .receive(on: DispatchQueue.main) .sink( receiveCompletion: { [weak self] completion in self?.isLoading = false if case .failure(let error) = completion { self?.errorMessage = error.localizedDescription } }, receiveValue: { [weak self] users in self?.users = users } ) .store(in: &cancellables) } } // Service class APIService: APIServiceProtocol { func fetchUsers() -> AnyPublisher<[User], Error> { let url = URL(string: "https://api.example.com/users")! return URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .decode(type: [User].self, decoder: JSONDecoder()) .eraseToAnyPublisher() } } // View struct UserListView: View { @StateObject private var viewModel = UserListViewModel() var body: some View { List(viewModel.users) { user in Text(user.name) } .onAppear { viewModel.fetchUsers() } .overlay { if viewModel.isLoading { ProgressView() } } .alert("Error", isPresented: .constant(viewModel.errorMessage != nil)) { Button("OK") {} } message: { Text(viewModel.errorMessage ?? "") } } } ``` -------------------------------- ### Struct (Value Type) Example Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/types.md Demonstrates a struct as a value type. Assigning a struct to a new variable creates an independent copy. ```swift struct Point { var x: Double var y: Double } var p1 = Point(x: 0, y: 0) var p2 = p1 // p2 is a COPY of p1 p2.x = 5 // Mutating p2 does NOT affect p1 print(p1.x, p2.x) // 0 5 ``` -------------------------------- ### Custom Property Wrapper for UserDefaults Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Demonstrates creating a custom property wrapper, @UserDefault, to simplify reading and writing values to UserDefaults. The example shows its use in a SettingsView for a username property. ```swift @propertyWrapper struct UserDefault { let key: String let defaultValue: T var wrappedValue: T { get { UserDefaults.standard.object(forKey: key) as? T ?? defaultValue } nonmutating set { UserDefaults.standard.set(newValue, forKey: key) } } } struct SettingsView: View { @UserDefault(key: "username", defaultValue: "Guest") var username: String var body: some View { TextField("Username", text: $username) } } ``` -------------------------------- ### Framework API Design with Access Control Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/access_control.md An example of designing a public API for a framework using different access levels for its components. ```swift public struct APIClient { public init() { } // Public API public func fetch(_ endpoint: String) async throws -> T { let data = await performRequest(endpoint) return try decode(data) } // Internal implementation internal func performRequest(_ endpoint: String) async -> Data { // ... } // Private helper private func decode(_ data: Data) throws -> T { // ... } } ``` -------------------------------- ### Defaulted Parameters for Simpler Calls Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/functions.md Provide sensible defaults for commonly used arguments to simplify function calls. This example shows a date initializer with optional locale and time zone. ```swift extension Date { convenience init?(iso8601 string: String, locale: Locale? = nil, timeZone: TimeZone? = nil) { ... } } // Simple call let date = Date(iso8601: "2025-04-01T12:00:00Z") ``` -------------------------------- ### While and Repeat-While Loops in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use while loops for conditions that may not be met initially, and repeat-while loops to ensure at least one execution. Examples include counting and dice rolling. ```swift // While var count = 0 while count < 5 { print(count) count += 1 } // Repeat-while (executes at least once) var dice = 0 repeat { dice = Int.random(in: 1...6) print("Rolled: \(dice)") } while dice != 6 ``` -------------------------------- ### Capture List Syntax for Reference Management Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/closures.md Provides examples of capture list syntax (`[self]`, `[weak self]`, `[unowned self]`) used within closures to manage object references and prevent retain cycles. ```swift // Strong reference (default) { [self] in ... } // Weak reference { [weak self] in ... } // Unowned reference { [unowned self] in ... } // Multiple captures { [weak self, unowned delegate = self.delegate!] in ... } ``` -------------------------------- ### Plugin Product Definition Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Demonstrates how to define a plugin product. ```swift .plugin( name: "MyPlugin", targets: ["MyPlugin"]) ``` -------------------------------- ### Access Level Decision Tree Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/access_control.md A flowchart-like representation to guide the selection of appropriate Swift access control modifiers. ```text Is this part of public API? ├── YES → Should it be subclassable outside module? │ ├── YES → Use open │ └── NO → Use public └── NO → Same module only? ├── YES → Use internal (default) └── NO → Same file only? ├── YES → Use fileprivate └── NO → Use private ``` -------------------------------- ### Run Swift Onboard Tool Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_onboard/SKILL.md Execute the Swift Onboard script from the project root to generate or update the ARCHITECTURE.md file. ```bash scripts/swift_onboard ``` -------------------------------- ### Build and Distribute XCFramework Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Create an XCFramework from a framework, zip it for distribution, and compute its checksum. ```bash xcodebuild -create-xcframework \ -framework MyFramework.framework \ -output MyFramework.xcframework ``` ```bash zip -r MyFramework.xcframework.zip MyFramework.xcframework ``` ```bash swift package compute-checksum MyFramework.xcframework.zip ``` -------------------------------- ### Executable Product Definition Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Shows how to define an executable product for command-line tools. ```swift .executable( name: "CLI-Tool", targets: ["CLI-Tool"]) ``` -------------------------------- ### Library Product Definitions Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Illustrates how to define library products, including static, dynamic, and libraries composed of multiple targets. ```swift // Static library (default) .library( name: "MyLibrary", targets: ["MyLibrary"]) // Dynamic library .library( name: "MyLibrary", type: .dynamic, targets: ["MyLibrary"]) // Multiple targets .library( name: "Core", targets: ["Core", "Utils"]) ``` -------------------------------- ### Custom SerialExecutor Isolation Validation Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/references/swift6_strict_mode.md Example of a custom SerialExecutor. Swift 6 validates that isolation rules are not breached when using custom executors. ```swift final class ImageQueueExecutor: SerialExecutor { private let queue = DispatchQueue(label: "image.queue") func submit(_ job: @escaping () -> Void) { queue.async(execute: job) } // Swift 6 validates isolation doesn't breach } ``` -------------------------------- ### Binary Target Definitions Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Shows how to define binary targets for pre-compiled frameworks, either from a URL with a checksum or a local path. ```swift .binaryTarget( name: "Framework", url: "https://example.com/Framework.xcframework.zip", checksum: "abc123..." ) // Or local .binaryTarget( name: "Framework", path: "Frameworks/Framework.xcframework") ``` -------------------------------- ### DropFirst Operator in Swift Combine Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/operators.md Omits the first N elements from a publisher. Use to skip initial values, like setup or boilerplate. ```swift publisher .dropFirst(3) ``` -------------------------------- ### Execute Swift Ask Wrapper Script Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_ask/SKILL.md Run the `swift_ask` wrapper script from the skill's `scripts/` folder by providing your natural language question as an argument. Ensure the `SWIFTZILLA_API_KEY` environment variable is set. ```bash scripts/swift_ask "" ``` -------------------------------- ### Swift Filter Dictionary Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_dictionary.md Creates a new dictionary containing only the key-value pairs that satisfy a given predicate. This example filters for scores greater than 7. ```swift let scores = ["alice": 10, "bob": 5, "carol": 12] let highScores = scores.filter { $0.value > 7 } // ["alice": 10, "carol": 12] ``` -------------------------------- ### GitHub Publishing Initial Commit Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Initialize a Git repository, commit your package files, and push to a remote origin on GitHub. ```bash git init git add . git commit -m "Initial commit" git remote add origin https://github.com/username/MyPackage.git git push -u origin main ``` -------------------------------- ### Resource Processing and Copying Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Demonstrates how to include resources in a package, distinguishing between processing (e.g., asset catalogs) and copying (e.g., data files). ```swift // Process (transforms during build) resources: [ .process("Assets.xcassets"), .process("Localization"), ] // Copy (preserves as-is) resources: [ .copy("Data/config.json"), ] ``` -------------------------------- ### Standard Swift Package Directory Structure Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/SKILL.md Illustrates the typical file and directory layout for a Swift package. This structure helps in organizing source code, tests, and the package manifest. ```text MyPackage/ ├── Package.swift # Package manifest ├── Sources/ │ └── MyLibrary/ │ └── MyLibrary.swift ├── Tests/ │ └── MyLibraryTests/ │ └── MyLibraryTests.swift └── README.md ``` -------------------------------- ### Swift Transform Dictionary Keys Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_dictionary.md Creates a new dictionary by transforming the keys of an existing dictionary. This example converts string keys to uppercase using `uppercased()`. ```swift let raw: [String: Int] = ["a": 1, "b": 2, "c": 3] let capitalized = Dictionary(uniqueKeysWithValues: raw.map { ($0.key.uppercased(), $0.value) }) // ["A": 1, "B": 2, "C": 3] ``` -------------------------------- ### Testing an Async Property Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/async_testing.md Tests a class property that provides asynchronous access to data. This example shows how to `await` a property getter that performs an asynchronous operation and throws. ```swift class DataLoader { var data: Data { get async throws { try await fetchData() } } } @Test func testAsyncProperty() async throws { let loader = DataLoader() let data = try await loader.data #expect(!data.isEmpty) } ``` -------------------------------- ### Switch Statement with Tuple Patterns in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use switch statements with tuple patterns to match specific combinations of values. This example matches points on a 2D plane. ```swift let point = (1, 1) switch point { case (0, 0): print("Origin") case (_, 0): print("On x-axis") case (0, _): print("On y-axis") case (-2...2, -2...2): print("Near origin") // This prints default: print("Far away") } ``` -------------------------------- ### Swift String Creation Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/strings.md Demonstrates how to create strings using literals, empty string initializers, and handling special characters including multiline strings with triple quotes. ```swift // Literal let greeting = "Hello, World!" // Empty var empty = "" var alsoEmpty = String() // With special characters let quote = "He said, \"Hello\"" let path = "C:\\Users\\Name" let multiline = """ This is a multiline string with indentation """ ``` -------------------------------- ### Switch Statement with Character Patterns in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use switch statements for exhaustive pattern matching on values like characters. This example demonstrates matching vowels and consonants. ```swift let character: Character = "a" switch character { case "a", "e", "i", "o", "u": print("Vowel") case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": print("Consonant") default: print("Other") } ``` -------------------------------- ### Running Swift Tests via Command Line Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/SKILL.md Provides common command-line commands for running Swift tests, including running all tests, filtering by name, filtering by tag, and enabling verbose output. ```bash # Run all tests swift test # Run specific test swift test --filter addition # Run tests by tag swift test --tag unit # Run with verbose output swift test --verbose ``` -------------------------------- ### Basic Combine Publishers in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/SKILL.md Demonstrates the creation of various publisher types in Combine, including @Published properties, CurrentValueSubject, PassthroughSubject, Just, and Future. Ensure Combine framework is imported. ```swift import Combine // Published property @Published var username: String = "" // CurrentValueSubject let subject = CurrentValueSubject("initial") // PassthroughSubject let passthrough = PassthroughSubject() // Just publisher let just = Just("value") // Future publisher let future = Future { promise in promise(.success("result")) } ``` -------------------------------- ### Swift Dictionary Basic Operations Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_dictionary.md Demonstrates initializing a dictionary, checking for key existence using `keys.contains()`, accessing values with a default, and mutating a value. ```swift var scores: [String: Int] = ["alice": 10, "bob": 12, "carol": 8] // Fast key existence test if scores.keys.contains("bob") { print("Bob is in the dictionary") } // Safe access with default let daveScore = scores["dave", default: 0] // 0 // Mutate value scores["alice"] = 15 ``` -------------------------------- ### For-In Loop Iteration in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use for-in loops to iterate over sequences like arrays. This example shows iterating over names and also iterating with an index using .enumerated(). ```swift let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { print("Hello, \(name)!") } // With index for (index, name) in names.enumerated() { print("\(index + 1): \(name)") } ``` -------------------------------- ### Switch Statement with Where Clause in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use switch statements with a 'where' clause to add additional conditions to a pattern match. This example checks for points on specific diagonal lines. ```swift let point = (x: 10, y: -10) switch point { case let (x, y) where x == y: print("On line x=y") case let (x, y) where x == -y: print("On line x=-y") // This prints default: print("Somewhere else") } ``` -------------------------------- ### Form Validation with Combine Publishers Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/operators.md This example shows how to perform form validation using Combine publishers. It combines the validity of email and password fields to enable a submit button. ```swift let isEmailValid = emailPublisher .map { $0.contains("@") } .eraseToAnyPublisher() let isPasswordValid = passwordPublisher .map { $0.count >= 8 } .eraseToAnyPublisher() isEmailValid .combineLatest(isPasswordValid) .map { $0 && $1 } .assign(to: \.isSubmitEnabled, on: submitButton) .store(in: &cancellables) ``` -------------------------------- ### Swift Substring Creation and Conversion Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/strings.md Demonstrates how to create substrings using range operators and convert them back to String objects. ```swift let greeting = "Hello, World!" // Creating substrings let comma = greeting.firstIndex(of: ",")! let beginning = greeting[..) -> Void) { // ... } // After (async/await) func fetchUser() async throws -> User { // ... } ``` -------------------------------- ### Switch Statement with Value Binding in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use switch statements with value binding to extract values from matched cases. This example binds the message from a success case and the code from an error case. ```swift let status = (code: 404, message: "Not Found") switch status { case (200, let message): print("Success: \(message)") case (let code, _): print("Error \(code)") // This prints } ``` -------------------------------- ### Basic Package.swift Manifest Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/SKILL.md Defines a Swift package with a library product, specifying platforms, dependencies, and targets. Use this as a template for creating new Swift packages. ```swift // swift-tools-version:5.9 import PackageDescription let package = Package( name: "MyLibrary", platforms: [.iOS(.v15), .macOS(.v12)], products: [ .library( name: "MyLibrary", targets: ["MyLibrary"]) ], dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.8.0"), ], targets: [ .target( name: "MyLibrary", dependencies: [ .product(name: "Alamofire", package: "Alamofire") ]) , .testTarget( name: "MyLibraryTests", dependencies: ["MyLibrary"]) ] ) ``` -------------------------------- ### Async Let for Concurrent Operations in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/references/async_await.md Allows multiple asynchronous operations to start concurrently using `async let`. Results are then retrieved using `await` on each declared async let binding. ```swift func loadData() async throws -> (User, Settings) { async let userTask = fetchUser() async let settingsTask = fetchSettings() // Both fetch concurrently let user = try await userTask let settings = try await settingsTask return (user, settings) } ``` -------------------------------- ### Package.swift Binary Target Configuration Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Define a binary target in your Package.swift file, specifying the URL and checksum for the zipped XCFramework. ```swift .binaryTarget( name: "MyBinary", url: "https://example.com/MyBinary.xcframework.zip", checksum: "abc123..." ) ``` -------------------------------- ### Parameterized Swift Test Examples Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/SKILL.md Illustrates parameterized tests, allowing a single test function to be executed multiple times with different sets of arguments. The 'arguments' parameter can take arrays of values or tuples. ```swift @Test(arguments: ["hello", "world", "swift"]) func stringLength(string: String) { #expect(string.count > 0) } @Test(arguments: zip([1, 2, 3], [1, 4, 9])) func squared(input: Int, expected: Int) { #expect(input * input == expected) } ``` -------------------------------- ### Execute SwiftZilla Ask Tool Source: https://github.com/swiftzilla/skills/blob/main/skills/swiftzilla/references/ask.md This command executes the SwiftZilla Ask tool to query the knowledge base. Replace "" with your specific question. ```bash ./swiftzilla/scripts/swiftzilla ask "" ``` -------------------------------- ### Running Async Operations Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/SKILL.md Shows different ways to initiate and manage asynchronous operations: fire-and-forget, background priority tasks, and task cancellation. ```swift // Fire-and-forget Task { let result = await asyncOperation() } // With priority Task(priority: .background) { await heavyComputation() } // With cancellation let task = Task { try await longRunningOperation() } task.cancel() ``` -------------------------------- ### SwiftUI @Environment for Shared Values Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Use @Environment to access shared values from the SwiftUI environment, such as color scheme, dismiss actions, or managed object contexts. The example demonstrates accessing colorScheme and dismiss. ```swift struct EnvironmentView: View { @Environment(\.colorScheme) var colorScheme @Environment(\.dismiss) var dismiss @Environment(\.managedObjectContext) var context var body: some View { VStack { Text(colorScheme == .dark ? "Dark Mode" : "Light Mode") Button("Dismiss") { dismiss() } } } } ``` -------------------------------- ### Using Sets with Custom Hashable Types Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_set.md Shows how to use custom structs as elements in a Set by conforming to the `Hashable` protocol. Membership testing is demonstrated. ```swift struct Point: Hashable { let x: Int let y: Int } let points: Set = [Point(x: 1, y: 2), Point(x: 3, y: 4)] points.contains(Point(x: 1, y: 2)) // true ``` -------------------------------- ### SwiftUI @Binding for Shared State Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Use @Binding for a two-way reference to external state, allowing child views to modify state owned by a parent. The example demonstrates a ToggleView modifying a boolean state in its ParentView. ```swift struct ToggleView: View { @Binding var isOn: Bool var body: some View { Toggle("Enable Feature", isOn: $isOn) } } struct ParentView: View { @State private var featureEnabled = false var body: some View { ToggleView(isOn: $featureEnabled) } } ``` -------------------------------- ### Basic Set Creation in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_set.md Demonstrates creating a Set of integers and creating a Set from an array, which automatically removes duplicate elements. ```swift let primes: Set = [2, 3, 5, 7] // From array (removes duplicates) let uniqueIDs = Set([101, 102, 101, 103, 102]) ``` -------------------------------- ### SwiftUI @State for Local State Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Use @State for view-local mutable state. It's suitable for value types whose changes should trigger UI updates. The example shows a counter that increments on button tap. ```swift struct CounterView: View { @State private var count = 0 var body: some View { VStack { Text("Count: \(count)") Button("Increment") { count += 1 } } } // Custom initializer init(initialCount: Int) { _count = State(initialValue: initialCount) } } ``` -------------------------------- ### Explain Current Execution Frame Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_debug/SKILL.md Understand the current execution context by explaining what the code does and why it's executing. ```lldb sz_explain ``` -------------------------------- ### Range Loops in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/control_flow.md Use range loops for iterating a specific number of times. Examples include closed ranges (1...5), half-open ranges (0..<3), and stride for custom increments. ```swift // Closed range for index in 1...5 { print("\(index) times 5 is \(index * 5)") } // Half-open range for i in 0..<3 { print(i) // 0, 1, 2 } // Stride for tick in stride(from: 0, to: 60, by: 5) { print(tick) } ``` -------------------------------- ### Open vs Public in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/access_control.md Illustrates the difference between 'open' and 'public' access levels, specifically regarding subclassing outside the module. ```swift // Can be subclassed outside the module open class Shape { open func draw() { } public func calculateArea() { } } // Cannot be subclassed outside the module public class Rectangle: Shape { public override func draw() { } } ``` -------------------------------- ### Sharing a Publisher with Share and Multicast Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/publishers_subscribers.md Use 'share()' combined with 'multicast()' to create a publisher that is shared among multiple subscribers. 'share()' automatically connects and disconnects, while 'multicast()' uses a subject to broadcast. ```swift let shared = publisher .share() .multicast { PassthroughSubject() } ``` -------------------------------- ### SwiftUI @StateObject for Owned Reference Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Use @StateObject to create and own a reference type (ObservableObject) that persists for the lifetime of the view, even across view updates. This ensures the object is not recreated unnecessarily. The example shows PersistentView managing its own ViewModel. ```swift struct PersistentView: View { @StateObject private var viewModel = ViewModel() var body: some View { VStack { Text("Count: \(viewModel.count)") Button("Increment") { viewModel.increment() } } } } ``` -------------------------------- ### Swift String Comparison Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/strings.md Shows how to perform case-sensitive and case-insensitive comparisons, and check for prefixes and suffixes. ```swift let word = "cafe" // Case-sensitive word == "cafe" // true word == "Cafe" // false // Case-insensitive word.caseInsensitiveCompare("CAFE") == .orderedSame // true // Has prefix/suffix word.hasPrefix("ca") // true word.hasSuffix("fe") // true ``` -------------------------------- ### SwiftUI @ObservedObject for External State Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_swiftui/references/property_wrappers.md Use @ObservedObject to observe an external reference type (ObservableObject) that notifies changes. The view updates when @Published properties within the observed object change. This example shows a ContentView observing a ViewModel. ```swift class ViewModel: ObservableObject { @Published var count = 0 @Published var message = "" func increment() { count += 1 } } struct ContentView: View { @ObservedObject var viewModel: ViewModel var body: some View { VStack { Text("Count: \(viewModel.count)") Button("Increment") { viewModel.increment() } } } } ``` -------------------------------- ### Organize Tests Across Multiple Files Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/organization.md For larger projects, distribute tests into separate files based on the functionality they cover, with each file often containing a single suite. ```swift // AdditionTests.swift @Suite("Addition") struct AdditionTests { } // SubtractionTests.swift @Suite("Subtraction") struct SubtractionTests { } // MultiplicationTests.swift @Suite("Multiplication") struct MultiplicationTests { } ``` -------------------------------- ### Run Tests by Tag via Command Line Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/organization.md Use the `swift test --tag ` command to execute tests marked with specific tags. Multiple tags can be combined with `--tag`. ```bash # Run only unit tests swift test --tag unit # Run integration tests swift test --tag integration # Run tests with multiple tags swift test --tag unit --tag api # Exclude slow tests swift test --skip-tag slow ``` -------------------------------- ### Version Tagging with Git Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Use Git to create and push version tags for your Swift package releases. Supports standard and pre-release versions. ```bash git tag 1.0.0 git push origin 1.0.0 ``` ```bash git tag -a 1.0.0 -m "Initial release" git push origin 1.0.0 ``` ```bash # Beta git tag 1.0.0-beta.1 ``` ```bash # Release Candidate git tag 1.0.0-rc.1 ``` -------------------------------- ### Basic Package.swift Structure Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Defines the fundamental structure of a Package.swift file, including package name, supported platforms, products, dependencies, targets, and Swift language versions. ```swift // swift-tools-version:5.9 import PackageDescription let package = Package( name: "PackageName", platforms: [.iOS(.v15), .macOS(.v13), .watchOS(.v9), .tvOS(.v16)], products: [ // Products define executables and libraries ], dependencies: [ // Dependencies on other packages ], targets: [ // Targets are basic building blocks ], swiftLanguageVersions: [.v5] ) ``` -------------------------------- ### Swift Closure Type Signatures Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/closures.md Illustrates the type signatures for Swift closures, showing how to define the parameter types and return type for different closure scenarios. ```swift // No parameters, no return value () -> Void // Single parameter, returns Bool (Int) -> Bool // Multiple parameters, returns String (Int, String) -> String ``` -------------------------------- ### Swift String Indexing and Iteration Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/strings.md Explains how to work with string indices, find specific indices, and iterate over characters within a string. ```swift let greeting = "Guten Tag!" // String indices are not integers! let index = greeting.index(greeting.startIndex, offsetBy: 7) greeting[index] // "a" // Finding indices if let comma = greeting.firstIndex(of: ",") { print(greeting[greeting.startIndex.. Bool in return a < b } // Type inference numbers.sorted { a, b in a < b } // Shorthand argument names numbers.sorted { $0 < $1 } // Operator method numbers.sorted(by: <) ``` -------------------------------- ### Platform Specifications Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Specifies the minimum deployment target for various Apple platforms. ```swift platforms: [ .iOS(.v14), .macOS(.v11), .watchOS(.v7), .tvOS(.v14), .macCatalyst(.v14), .driverKit(.v21), ] ``` -------------------------------- ### Discover Tests by Tag via Command Line Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/organization.md Run tests associated with specific tags using the `swift test --tag ` command. Multiple tags can be specified to run tests matching any of the tags. ```bash swift test --tag unit swift test --tag api --tag slow ``` -------------------------------- ### Swift Generic Function and Type Syntax Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/generics.md Demonstrates the basic syntax for defining a generic function and a generic struct in Swift. These allow for placeholder types that can be replaced with concrete types later. ```swift // Generic function func identity(value: T) -> T { return value } // Generic type struct Stack { private var items: [Element] = [] mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element? { return items.popLast() } } ``` -------------------------------- ### Factory Method Style Initialization Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/functions.md Use factory method style for creating instances when it improves readability, often by using descriptive parameter names in the initializer. ```swift struct Size { init(width: CGFloat, height: CGFloat) { ... } } let size = Size(width: 100, height: 200) ``` -------------------------------- ### DocC Documentation Generation Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/publishing.md Generate documentation for your Swift package using the Swift build tools or the DocC command-line tool. ```bash swift build --target MyPackage swift package generate-documentation ``` ```bash xcrun docc convert MyPackage.docc \ --fallback-display-name MyPackage \ --fallback-bundle-identifier com.example.MyPackage \ --output-dir docs ``` -------------------------------- ### Swift Array Basic Operations Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_array.md Demonstrates common array transformations using map, filter, and reduce, along with enumerating elements with their indices. ```swift let numbers = [1, 2, 3, 4, 5] // Transform let doubled = numbers.map { $0 * 2 } // [2, 4, 6, 8, 10] // Filter let even = numbers.filter { $0.isMultiple(of: 2) } // [2, 4] // Reduce (sum) let sum = numbers.reduce(0, +) // 15 // Enumerate numbers.enumerated().forEach { index, value in print("Item \(index) = \(value)") } ``` -------------------------------- ### Basic Swift Access Levels Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/access_control.md Demonstrates the usage of public, fileprivate, private, and internal access modifiers on class members and initializers. ```swift public class Person { // Visible everywhere public var name: String // Visible only in this file fileprivate var age: Int // Visible only to this class private init() { } // Visible within same module internal static let defaultGreeting = "Hello" } ``` -------------------------------- ### Autoconnecting a Connectable Publisher Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/publishers_subscribers.md Use 'makeConnectable()' followed by 'autoconnect()' to create a publisher that automatically connects to its upstream publisher as soon as the first subscriber appears. This simplifies the management of connectable publishers. ```swift let connectable = publisher .makeConnectable() .autoconnect() ``` -------------------------------- ### Swift Protocol Definition and Conformance Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/protocols.md Defines a protocol with properties, methods, and initializers, and shows a struct conforming to it. ```swift // Protocol definition protocol MyProtocol { var property: String { get set } func method() -> Int init(parameter: String) } // Conformance struct MyType: MyProtocol { var property: String func method() -> Int { return 0 } init(parameter: String) { self.property = parameter } } ``` -------------------------------- ### Define a Basic Swift Protocol Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/protocols.md Define a protocol with required properties and methods. Structs or classes adopt this protocol to provide concrete implementations. ```swift protocol Drawable { func draw() var color: String { get set } } struct Circle: Drawable { var color: String var radius: Double func draw() { print("Drawing \(color) circle with radius \(radius)") } } ``` -------------------------------- ### Enabling Swift 6 Language Mode in Package.swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/references/swift6_strict_mode.md Shows how to enable Swift 6 language mode in your project's Package.swift file. This is the first step in migrating to Swift 6. ```swift swiftSettings: [ .swiftLanguageVersion(.v6) ] ``` -------------------------------- ### Swift Existentials (any Protocol) for Heterogeneous Collections Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/protocols.md Use the 'any Protocol' syntax to create collections that can hold instances of different types conforming to the same protocol. This enables dynamic dispatch. ```swift protocol Speaker { func speak(_ message: String) } // Heterogeneous array let audience: [any Speaker] = [ SimpleSpeaker(), RobotSpeaker(), WhisperingSpeaker() ] for participant in audience { participant.speak("Hello!") } ``` -------------------------------- ### Subset and Superset Checks in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_set.md Illustrates how to check for subset, superset, and disjoint relationships between Sets using methods like `isSuperset(of:)`, `isSubset(of:)`, and `isDisjoint(with:)`. ```swift let evenNumbers: Set = [0, 2, 4, 6, 8] let smallNumbers: Set = [0, 2, 4] evenNumbers.isSuperset(of: smallNumbers) // true smallNumbers.isSubset(of: evenNumbers) // true evenNumbers.isDisjoint(with: [1, 3, 5]) // true ``` -------------------------------- ### Just Publisher Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/publishers_subscribers.md Use 'Just' to create a publisher that emits a single value and then completes immediately. It's useful for synchronous operations that produce one result. ```swift let publisher = Just("Hello") .sink { value in print(value) // "Hello" } ``` -------------------------------- ### Swift String Inspection Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/strings.md Illustrates how to inspect string properties such as emptiness, count, and check for prefixes, suffixes, and containment. ```swift let str = "Hello, Swift!" // Properties print(str.isEmpty) // false print(str.count) // 13 print(str.hasPrefix("Hello")) // true print(str.hasSuffix("!")) // true print(str.contains("Swift")) // true ``` -------------------------------- ### Linker Settings Configuration Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_package_manager/references/package_structure.md Configures linker settings, such as linking against system frameworks or libraries, and specifying custom library search paths. ```swift linkerSettings: [ .linkedFramework("UIKit"), .linkedFramework("CoreData", .when(platforms: [.iOS, .macOS])), .linkedLibrary("z"), .unsafeFlags(["-L/path/to/lib"]), ] ``` -------------------------------- ### Basic Async Test Function Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_testing/references/async_testing.md Demonstrates a simple asynchronous test function that fetches user data and asserts its properties. Ensure your API client is available in the scope. ```swift import Testing @Test func fetchUser() async throws { let user = try await api.fetchUser(id: 1) #expect(user.id == 1) #expect(user.name == "Ada") } ``` -------------------------------- ### Timer Publisher Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_combine/references/integration.md Create a repeating timer publisher that emits events on the main run loop. ```swift Timer.publish(every: 1.0, on: .main, in: .common) .autoconnect() .sink { date in print("Tick: \(date)") } .store(in: &cancellables) ``` -------------------------------- ### AsyncSequence for Iterating Async Data in Swift Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_concurrency/references/async_await.md Demonstrates iterating over asynchronous sequences like URL content lines or custom AsyncStreams. Use `for await` for non-throwing sequences and `for try await` for those that can throw errors. ```swift // Iterate over async stream for try await line in url.lines { print(line) } // AsyncStream let stream = AsyncStream { continuation in for i in 1...5 { continuation.yield(i) } continuation.finish() } for await value in stream { print(value) // 1, 2, 3, 4, 5 } ``` -------------------------------- ### Sync Codebase Index Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_context/SKILL.md Rebuilds the encrypted semantic index for the project. Run this command when project files have changed significantly or if the cache is missing or stale. ```bash scripts/swift_context sync --path ``` -------------------------------- ### Swift Protocol Composition Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_style/references/protocols.md Demonstrates using protocol composition with the '&' operator for types that must conform to multiple protocols. ```swift // Composition func use(item: some ProtocolA & ProtocolB) { } ``` -------------------------------- ### Inserting Elements and Checking Return Value Source: https://github.com/swiftzilla/skills/blob/main/skills/swift_structure/references/collections_set.md Demonstrates inserting a new element into a Set and checking the returned tuple to determine if the insertion was successful and what the element is. ```swift var letters: Set = ["a", "b"] let (inserted, member) = letters.insert("c") print(inserted) // true (new element added) print(member) // "c" let (alreadyInserted, _) = letters.insert("a") print(alreadyInserted) // false (already existed) ```