### Install Swift Concurrency Skill Source: https://www.swift.org/documentation/articles/getting-started-with-cursor-swift.html Example command to install the Swift Concurrency agent skill. This command specifies the repository and the name of the skill to be added. ```bash npx skills add https://github.com/avdlee/swift-concurrency-agent-skill --skill swift-concurrency ``` -------------------------------- ### Example Program Using AsyncHTTPClient Source: https://www.swift.org/documentation/server/guides/allocations.html An example Swift program that performs ten HTTP GET requests using AsyncHTTPClient. It demonstrates setting up the client, handling requests sequentially, and managing event loops and promises. ```swift import AsyncHTTPClient import NIO import Logging let urls = Array(repeating:"http://httpbin.org/get", count: 10) var logger = Logger(label: "ahc-alloc-demo") logger.info("running HTTP requests", metadata: ["count": "\(urls.count)"]) MultiThreadedEventLoopGroup.withCurrentThreadAsEventLoop { eventLoop in let httpClient = HTTPClient(eventLoopGroupProvider: .shared(eventLoop), backgroundActivityLogger: logger) func doRemainingRequests(_ remaining: ArraySlice, overallResult: EventLoopPromise, eventLoop: EventLoop) { var remaining = remaining if let first = remaining.popFirst() { httpClient.get(url: first, logger: logger).map { [remaining] _ in eventLoop.execute { // for shorter stacks doRemainingRequests(remaining, overallResult: overallResult, eventLoop: eventLoop) } }.whenFailure { error in overallResult.fail(error) } } else { return overallResult.succeed(()) } } let promise = eventLoop.makePromise(of: Void.self) // Kick off the process doRemainingRequests(urls[...], overallResult: promise, eventLoop: eventLoop) promise.futureResult.whenComplete { result in switch result { case .success: logger.info("all HTTP requests succeeded") case .failure(let error): logger.error("HTTP request failure", metadata: ["error": "\(error)"]) } httpClient.shutdown { maybeError in if let error = maybeError { logger.error("AHC shutdown failed", metadata: ["error": "\(error)"]) } eventLoop.shutdownGracefully { maybeError in if let error = maybeError { logger.error("EventLoop shutdown failed", metadata: ["error": "\(error)"]) } } } } } logger.info("exiting") ``` -------------------------------- ### Install Swift SDK for Android Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Downloads and installs the Swift SDK bundle for Android using the `swift sdk install` command. Requires a URL to the artifact bundle and its checksum. ```bash $ swift sdk install https://download.swift.org/swift-6.3.2-release/android-sdk/swift-6.3.2-RELEASE/swift-6.3.2-RELEASE_android.artifactbundle.tar.gz --checksum 939e933549d12d28f2e0bf71019d734d309859e9773c572657ce565a81f85d68 ``` -------------------------------- ### List Installed Swift SDKs Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Lists all installed Swift SDKs, including the newly installed Android SDK. This command helps verify the installation. ```bash $ swift sdk list swift-6.3.2-RELEASE_android ``` -------------------------------- ### Install Swift SDK for WebAssembly Source: https://www.swift.org/documentation/articles/wasm-getting-started.html Use this command to install the Swift SDKs for WebAssembly. Ensure you have the correct Swift toolchain version selected. ```bash swift sdk install https://download.swift.org/swift-6.3.2-release/wasm-sdk/swift-6.3.2-RELEASE/swift-6.3.2-RELEASE_wasm.artifactbundle.tar.gz --checksum a61f0584c93283589f8b2f42db05c1f9a182b506c2957271402992655591dd7c ``` -------------------------------- ### Install Docker on Amazon Linux 2 Source: https://www.swift.org/documentation/server/guides/deploying/aws.html Installs Docker and git on an Amazon Linux 2 instance and starts the Docker service. This is a prerequisite for compiling Swift code within a Docker container. ```bash sudo yum install docker git sudo usermod -a -G docker ec2-user sudo systemctl start docker ``` -------------------------------- ### Install Valgrind on Ubuntu Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html Use this command to install Valgrind on Ubuntu systems via apt-get. ```bash sudo apt-get install valgrind ``` -------------------------------- ### List Installed SDKs Source: https://www.swift.org/documentation/articles/static-linux-getting-started.html Lists all currently installed Static Linux SDKs on the system. ```bash $ swift sdk list ``` -------------------------------- ### Install Static Linux SDK Source: https://www.swift.org/documentation/articles/static-linux-getting-started.html Installs the Static Linux SDK from a URL or local file. Use the --checksum option for remote URLs to verify the archive's integrity. ```bash $ swift sdk install [--checksum ] ``` ```bash $ swift sdk install https://download.swift.org/swift-6.3.2-release/static-sdk/swift-6.3.2-RELEASE/swift-6.3.2-RELEASE_static-linux-0.1.0.artifactbundle.tar.gz --checksum 3fd798bef6f4408f1ea5a6f94ce4d4052830c4326ab85ebc04f983f01b3da407 ``` -------------------------------- ### Install Neovim using Snap Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Installs Neovim using the snap package manager. This is recommended for systems where the default repository version is outdated. ```bash $ sudo snap install nvim --classic $ nvim --version NVIM v0.11.5 Build type: RelWithDebInfo LuaJIT 2.1.1741730670 Run "nvim -V1 -v" for more info ``` -------------------------------- ### Install perf on Ubuntu Source: https://www.swift.org/documentation/server/guides/linux-perf.html Installs the generic Linux perf tools package on Ubuntu systems. ```bash apt-get update && apt-get -y install linux-tools-generic ``` -------------------------------- ### Deploy the SAM project Source: https://www.swift.org/documentation/server/guides/deploying/aws-sam-lambda.html Deploys your SAM project to AWS, creating Lambda functions, API Gateway, and DynamoDB. Use --guided for interactive setup. ```bash sam deploy --guided ``` -------------------------------- ### Clone Swift NIO Example Project Source: https://www.swift.org/documentation/server/guides/deploying/heroku.html Clones the Swift NIO example project from GitHub to your local machine. ```bash git clone https://github.com/apple/swift-nio ``` -------------------------------- ### Initialize lazy.nvim Setup Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Initializes lazy.nvim and specifies the directory where plugin specifications can be found. Ensure the 'plugins' directory exists. ```lua require("lazy").setup("plugins") ``` -------------------------------- ### Install Latest Swift Toolchain with Swiftly Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Installs the latest stable Swift release toolchain using the `swiftly` command-line tool. This is the recommended method for managing host toolchains on macOS and Linux. ```bash $ swiftly install latest Fetching the latest stable Swift release... Installing Swift 6.3.2 Installing package in user home directory... Swift 6.3.2 is installed successfully! $ swiftly use latest The global default toolchain has been set to `Swift 6.3.2` $ swift --version Apple Swift version 6.3.2 (swift-6.3.2-RELEASE) Target: arm64-apple-macosx26.0 ``` -------------------------------- ### Install perf on Fedora/RedHat Source: https://www.swift.org/documentation/server/guides/linux-perf.html Installs the perf package on Fedora and RedHat-based systems. ```bash yum install -y perf ``` -------------------------------- ### Verify perf installation Source: https://www.swift.org/documentation/server/guides/linux-perf.html Runs a basic perf stat command to verify the installation. Requires root privileges or sudo. ```bash sudo perf stat -- sleep 0.1 ``` -------------------------------- ### Example MongoDB Connection String Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html This is an example format for a MongoDB Atlas connection string. Replace placeholders with your actual credentials. ```text mongodb+srv://username:@mycluster.mongodb.net/?retryWrites=true&w=majority ``` -------------------------------- ### Install perf on Debian Source: https://www.swift.org/documentation/server/guides/linux-perf.html Installs the Linux perf package on Debian systems. ```bash apt-get update && apt-get -y install linux-perf ``` -------------------------------- ### Configure LuaSnip Plugin Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Sets up LuaSnip and loads snippets from the 'snippets' directory. Ensure LuaSnip is installed as a plugin. ```lua -- lua/plugins/snippets.lua return { { 'L3MON4D3/LuaSnip', conifg = function(opts) require('luasnip').setup(opts) require('luasnip.loaders.from_snipmate').load({ paths = "./snippets" }) end, }, } ``` -------------------------------- ### Structured Logging Example with Metadata Source: https://www.swift.org/documentation/server/guides/libraries/log-levels.html Demonstrates structured logging by passing dynamic information as metadata key-value pairs, making logs easier to parse. ```swift log.info("Accepted connection", metadata: [ "connection.id": "\(connection.id)", "connection.peer": "\(connection.peer)", "connections.total": "\(connections.count)" ]) // example output: // info [connection.id:?,connection.peer:?, connections.total:?] Accepted connection ``` -------------------------------- ### Install and configure swift-mode package Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `swift-mode` package and associates it with `.swift` files and the `swift` interpreter. This provides basic editing support for Swift code. ```emacs-lisp ;; Swift editing support (use-package swift-mode :ensure t :mode "\.swift\'" :interpreter "swift") ``` -------------------------------- ### Factory Method Naming Convention Source: https://www.swift.org/documentation/api-design-guidelines Begin names of factory methods with 'make'. This example demonstrates the correct convention for creating new instances. ```swift x.makeIterator() ``` -------------------------------- ### Create Procfile for Vapor App Source: https://www.swift.org/documentation/server/guides/deploying/heroku.html Example Procfile content for a Vapor application, specifying production environment, hostname, and port. ```bash web: Run serve --env production --hostname 0.0.0.0 --port $PORT ``` -------------------------------- ### Install and configure lsp-mode for language server integration Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `lsp-mode` package and sets up hooks for Swift mode. This enables integration with language servers like `sourcekit-lsp` for advanced features. ```emacs-lisp ;; Used to interface with swift-lsp. (use-package lsp-mode :ensure t :commands lsp :hook ((swift-mode . lsp))) ``` -------------------------------- ### Install and configure powerline for status bar Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `powerline` package and sets it to use the default theme. Powerline provides a sophisticated status line for Emacs. ```emacs-lisp ;; Powerline (use-package powerline :ensure t :config (powerline-default-theme)) ``` -------------------------------- ### Install binutils on Linux Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html Install the binutils package on a Linux system, which provides tools like addr2line for symbolication. This command is typically run with sudo. ```bash sudo apt install binutils ``` -------------------------------- ### Install and configure company mode for completion Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `company` package and enables global company mode. This provides an extensible, real-time code completion framework. ```emacs-lisp ;; Company mode (completion) (use-package company :ensure t :config (global-company-mode +1)) ``` -------------------------------- ### Install heaptrack on Ubuntu Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html Install the heaptrack tool on Ubuntu systems to profile heap memory usage and analyze memory leaks. This command is typically run with sudo. ```bash sudo apt-get install heaptrack ``` -------------------------------- ### Download and Configure Android NDK on Linux Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Automates the download, extraction, and configuration of the Android NDK for Linux. It sets the `ANDROID_NDK_HOME` environment variable and runs the setup script. ```bash $ cd ~/.swiftpm/swift-sdks/swift-6.3.2-RELEASE_android.artifactbundle/swift-android/ $ curl -fSL -o ndk.zip https://dl.google.com/android/repository/android-ndk-r27d-$(uname -s).zip $ unzip -qo ndk.zip $ export ANDROID_NDK_HOME=$PWD/android-ndk-r27d $ ./scripts/setup-android-sdk.sh ``` -------------------------------- ### Install nvim-cmp with lazy.nvim Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html This snippet tells lazy.nvim to download and lazily load the nvim-cmp plugin when entering insert mode. ```lua -- lua/plugins/codecompletion.lua return { { "hrsh7th/nvim-cmp", version = false, event = "InsertEnter", }, } ``` -------------------------------- ### Download and Configure Android NDK on macOS Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Automates the download, extraction, and configuration of the Android NDK for macOS. It sets the `ANDROID_NDK_HOME` environment variable and runs the setup script. ```bash $ cd ~/Library/org.swift.swiftpm/swift-sdks/swift-6.3.2-RELEASE_android.artifactbundle/swift-android/ $ curl -fSL -o ndk.zip https://dl.google.com/android/repository/android-ndk-r27d-$(uname -s).zip $ unzip -qo ndk.zip $ export ANDROID_NDK_HOME=$PWD/android-ndk-r27d $ ./scripts/setup-android-sdk.sh ``` -------------------------------- ### Initialize AWS Copilot Application Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Use this command to start a new AWS Copilot application. This sets up the basic structure for your project on AWS. ```bash copilot app init todo ``` -------------------------------- ### Create Neovim Configuration Directory and init.lua Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Sets up the necessary directory structure for Neovim's Lua configuration and creates the main init.lua file. ```bash $ mkdir -p ~/.config/nvim/lua && cd ~/.config/nvim $ nvim init.lua ``` -------------------------------- ### Initializer and Factory Method Naming Source: https://www.swift.org/documentation/api-design-guidelines The first argument to initializer and factory methods should not form a phrase starting with the base name. These examples show correct and incorrect ways to name such calls. ```swift let foreground = Color(red: 32, green: 64, blue: 128) let newPart = factory.makeWidget(gears: 42, spindles: 14) let ref = Link(target: destination) ``` ```swift let foreground = Color(havingRGBValuesRed: 32, green: 64, andBlue: 128) let newPart = factory.makeWidget(havingGearCount: 42, andSpindleCount: 14) let ref = Link(to: destination) ``` -------------------------------- ### Argument Labels for Prepositional Phrases Source: https://www.swift.org/documentation/api-design-guidelines Demonstrates using argument labels that start at the preposition when the first argument forms part of a prepositional phrase. ```swift a.move("toX": b, "y": c) a.fade("fromRed": b, "green": c, "blue": d) ``` -------------------------------- ### Create Procfile for NIO HTTP Server Source: https://www.swift.org/documentation/server/guides/deploying/heroku.html Defines how Heroku should run your application. This example is for the NIO HTTP Server, binding to all interfaces and using the Heroku-assigned port. ```bash echo "web: NIOHTTP1Server 0.0.0.0 $PORT" > Procfile ``` -------------------------------- ### Create Project Directory and Template File Source: https://www.swift.org/documentation/server/guides/deploying/aws-sam-lambda.html Initializes the project directory and creates the `template.yml` file for AWS SAM configuration. ```bash mkdir swift-lambda-api && cd swift-lambda-api touch template.yml ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Creates a new directory for your project and changes into it. This is the first step in setting up a new Vapor application. ```bash mkdir todo-app && cd todo-app ``` -------------------------------- ### Create and Build a New Project Source: https://www.swift.org/documentation/articles/static-linux-getting-started.html Creates a new executable Swift project and builds it locally. ```bash $ mkdir hello $ cd hello ``` ```bash $ swift package init --type executable ``` ```bash $ swift build Building for debugging... [8/8] Applying hello Build complete! (15.29s) $ .build/debug/hello Hello, world! ``` -------------------------------- ### Compile SwiftNIO Application using Docker Source: https://www.swift.org/documentation/server/guides/deploying/aws.html Compiles the SwiftNIO example HTTP server within a Docker container. This method isolates the build environment and ensures consistency. ```bash docker run --rm -v "$PWD:/workspace" -w /workspace swift:5.4-amazonlinux2 /bin/bash -cl ' \ swift build -v --static-swift-stdlib -c release ' ``` -------------------------------- ### Configure lsp-sourcekit for sourcekit-lsp integration Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `lsp-sourcekit` package and configures it to use the `find-sourcekit-lsp` function to locate the `sourcekit-lsp` executable. Requires `lsp-mode` to be loaded first. ```emacs-lisp ;; sourcekit-lsp support (use-package lsp-sourcekit :ensure t :after lsp-mode :custom (lsp-sourcekit-executable (find-sourcekit-lsp) "Find sourcekit-lsp")) ``` -------------------------------- ### Enable LSP and Set Keymaps Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Enables the sourcekit LSP and sets up keymaps for LSP actions like hover and go to definition upon LspAttach. ```lua -- lua/config/lsp.lua vim.lsp.enable("sourcekit") vim.api.nvim_create_autocmd('LspAttach', { desc = "LSP Actions", callback = function(args) vim.keymap.set("n", "K", vim.lsp.buf.hover, {noremap = true, silent = true}) vim.keymap.set("n", "gd", vim.lsp.buf.definition, {noremap = true, silent = true}) end, }) } ``` -------------------------------- ### Create Plugin and Config Directories Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html Creates the necessary 'lua/plugins' and 'lua/config' directories for organizing Neovim plugins and configurations. ```bash $ mkdir lua/plugins lua/config ``` -------------------------------- ### Build and Run Swift Executable Locally Source: https://www.swift.org/documentation/articles/swift-sdk-for-android-getting-started.html Build the Swift package for the host system and run the executable to verify it works. ```bash $ swift build Building for debugging... [8/8] Applying hello Build complete! (15.29s) $ .build/debug/hello Hello, world! ``` -------------------------------- ### Install Heroku CLI using Homebrew Source: https://www.swift.org/documentation/server/guides/deploying/heroku.html Installs the Heroku command-line interface tools using Homebrew on macOS. ```bash brew tap heroku/brew && brew install heroku ``` -------------------------------- ### Initialize SwiftPM Projects for Lambda Functions Source: https://www.swift.org/documentation/server/guides/deploying/aws-sam-lambda.html Use Swift Package Manager to initialize executable projects for your Lambda functions and create Dockerfiles. ```bash mkdir -p src/put-item cd src/put-item swift package init --type executable touch Dockerfile cd ../.. mkdir -p src/get-items cd src/get-items swift package init --type executable touch Dockerfile ``` -------------------------------- ### Install Emacs on Debian-based Linux Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Use this command to install the full Emacs package on Debian-based systems like Ubuntu. ```bash $ sudo apt-get install emacs ``` -------------------------------- ### Initialize a Swift Executable Package Source: https://www.swift.org/documentation/articles/wasm-getting-started.html Creates a new directory and initializes a Swift package of type executable. ```bash mkdir Hello cd Hello swift package init --type executable ``` -------------------------------- ### Non-Structured Logging Example Source: https://www.swift.org/documentation/server/guides/libraries/log-levels.html An example of a traditional, non-structured log message that includes dynamic information within the message string. ```swift log.info("Accepted connection \(connection.id) from \(connection.peer), total: \(connections.count)") ``` -------------------------------- ### Create .swift-version file Source: https://www.swift.org/documentation/server/guides/deploying/heroku.html Creates a '.swift-version' file in the project root, specifying the Swift version to be used (e.g., 5.9). ```bash echo "5.9" > .swift-version ``` -------------------------------- ### Perf Warning Example Source: https://www.swift.org/documentation/server/guides/allocations.html This is an example of a warning message indicating that perf has lost data chunks during recording. It suggests checking IO/CPU overload. ```text [ perf record: Woken up 189 times to write data ] Warning: Processed 4346 events and lost 144 chunks! Check IO/CPU overload! [ perf record: Captured and wrote 30.868 MB perf.data (3817 samples) ] ``` -------------------------------- ### Value Preserving Type Conversion Example Source: https://www.swift.org/documentation/api-design-guidelines This example shows a value-preserving type conversion where the first argument does not need a label to maintain fluency. ```swift let rgbForeground = RGBColor(cmykForeground) ``` -------------------------------- ### Install lsp-ui for enhanced LSP interface Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `lsp-ui` package, which provides user interface enhancements for `lsp-mode`, such as improved diagnostics and code navigation. ```emacs-lisp ;; lsp-mode's UI modules (use-package lsp-ui :ensure t) ``` -------------------------------- ### Create New User Source: https://www.swift.org/documentation/server/guides/deploying/digital-ocean.html Create a new non-root user named 'swift' to run your application. This user will not have sudo access for enhanced security. ```bash adduser swift ``` -------------------------------- ### Configure Swift Launch Configuration Source: https://www.swift.org/documentation/articles/getting-started-with-vscode-swift.html Sets up a launch configuration in `launch.json` to debug a Swift executable with custom arguments and a pre-launch build task. Ensure the `program` path and `preLaunchTask` match your project structure. ```json { "configurations": [ { "type": "swift", "name": "Debug swift-executable", "request": "launch", "args": ["--hello", "world"], "cwd": "${workspaceFolder}", "program": "${workspaceFolder}/.build/debug/swift-executable", "preLaunchTask": "swift: Build Debug swift-executable" } ] } ``` -------------------------------- ### Build the SAM project Source: https://www.swift.org/documentation/server/guides/deploying/aws-sam-lambda.html Builds your SAM project, compiling Swift code into Docker images. Run from the project root. ```bash sam build ``` -------------------------------- ### Install and configure rainbow-delimiters package Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `rainbow-delimiters` package and enables it for programming modes. This feature highlights nested delimiters with different colors, improving readability. ```emacs-lisp ;; Rainbow delimiters makes nested delimiters easier to understand (use-package rainbow-delimiters :ensure t :hook ((prog-mode . rainbow-delimiters-mode))) ``` -------------------------------- ### Create Addon Directory Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Creates the necessary directory structure for Copilot addons. ```bash mkdir -p copilot/api/addons ``` -------------------------------- ### Install Emacs on RedHat-based Linux Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Use this command to install Emacs on RedHat-based systems like Fedora. Use 'yum' on older versions if 'dnf' is not available. ```bash $ sudo dnf install emacs ``` -------------------------------- ### Install Emacs without X11 on Debian-based Linux Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Use this command to install Emacs without graphical support on Debian-based systems, suitable for servers or containers. ```bash $ sudo apt-get install emacs-nox ``` -------------------------------- ### Initializer Documentation Source: https://www.swift.org/documentation/api-design-guidelines Document what an initializer creates. ```swift /// **Creates** an instance containing `n` repetitions of `x`. init(count n: Int, repeatedElement x: Element) ``` -------------------------------- ### Valgrind Memory Leak Report Example Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html An example of a Valgrind Memcheck report showing heap summary and memory leak details, including stack traces. ```text ==1== Memcheck, a memory error detector ==1== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==1== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info ==1== Command: ./test ==1== ==1== ==1== HEAP SUMMARY: ==1== in use at exit: 824 bytes in 4 blocks ==1== total heap usage: 5 allocs, 1 frees, 73,528 bytes allocated ==1== ==1== 32 bytes in 1 blocks are definitely lost in loss record 1 of 4 ==1== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==1== by 0x52076B1: swift_slowAlloc (in /usr/lib/swift/linux/libswiftCore.so) ==1== by 0x5207721: swift_allocObject (in /usr/lib/swift/linux/libswiftCore.so) ==1== by 0x108E58: $s4test12MemoryLeakerCACycfC (in /tmp/test) ==1== by 0x10900E: $s4test28myFunctionDoingTheAllocationyyF (in /tmp/test) ==1== by 0x108CA3: main (in /tmp/test) ==1== ==1== LEAK SUMMARY: ==1== definitely lost: 32 bytes in 1 blocks ==1== indirectly lost: 0 bytes in 0 blocks ==1== possibly lost: 0 bytes in 0 blocks ==1== still reachable: 792 bytes in 3 blocks ==1== suppressed: 0 bytes in 0 blocks ==1== Reachable blocks (those to which a pointer was found) are not shown. ==1== To see them, rerun with: --leak-check=full --show-leak-kinds=all ==1== ==1== For counts of detected and suppressed errors, rerun with: -v ==1== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) ``` -------------------------------- ### Install and configure editorconfig package Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Ensures the `editorconfig` package is installed and enables its mode. This package helps maintain consistent coding styles across different editors. ```emacs-lisp ;; .editorconfig file support (use-package editorconfig :ensure t :config (editorconfig-mode +1)) ``` -------------------------------- ### Example LeakSanitizer Output Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html This is an example of the output you might see when LeakSanitizer detects memory leaks. It details the size and number of leaked objects and their allocation call stacks. ```text ================================================================= ==478==ERROR: LeakSanitizer: detected memory leaks Direct leak of 32 byte(s) in 1 object(s) allocated from: #0 0x55f72c21ac8d (/tmp/test+0x95c8d) #1 0x7f7e44e686b1 (/usr/lib/swift/linux/libswiftCore.so+0x3cb6b1) #2 0x55f72c24b2ce (/tmp/test+0xc62ce) #3 0x55f72c24a4c3 (/tmp/test+0xc54c3) #4 0x7f7e43aecb96 (/lib/x86_64-linux-gnu/libc.so.6+0x21b96) SUMMARY: AddressSanitizer: 32 byte(s) leaked in 1 allocation(s). ``` -------------------------------- ### Select Xcode Version and Build Project Source: https://www.swift.org/documentation/source-compatibility Commands to select a specific Xcode version and then build a project at a pinned commit using the compatibility check script. ```bash # Select Xcode 8.0 GM sudo xcode-select -s /Applications/Xcode.app # Build project at pinned commit against selected Xcode ./check project-path-field ``` -------------------------------- ### Demangled Swift Stack Trace Example Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html An example of a Valgrind stack trace after demangling Swift symbols, showing clearer function names and improving leak analysis. ```text ==1== 32 bytes in 1 blocks are definitely lost in loss record 1 of 4 ==1== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==1== by 0x52076B1: swift_slowAlloc (in /usr/lib/swift/linux/libswiftCore.so) ==1== by 0x5207721: swift_allocObject (in /usr/lib/swift/linux/libswiftCore.so) ==1== by 0x108E58: test.MemoryLeaker.__allocating_init() -> test.MemoryLeaker (in /tmp/test) ==1== by 0x10900E: test.myFunctionDoingTheAllocation() -> () (in /tmp/test) ==1== by 0x108CA3: main (in /tmp/test) ``` -------------------------------- ### Create Addon Parameters File Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Creates an empty YAML file to define parameters for the addon. ```bash touch copilot/api/addons/addons.parameters.yml ``` -------------------------------- ### C++ Umbrella Header Example Source: https://www.swift.org/documentation/cxx-interop/project-build-setup An example of a C++ umbrella header file that includes other C++ headers. This allows Swift to import the C++ target as a Clang module. ```c++ // Header file `cxxLibrary.h` #pragma once #include ``` -------------------------------- ### Build Application with Docker for Intel CPUs on Apple Silicon Source: https://www.swift.org/documentation/server/guides/building.html When building on an Apple Silicon Mac for Intel CPUs, append platform and QEMU CPU flags to the Docker run command to ensure compatibility. ```bash $ docker run -v "$PWD:/code" -w /code --platform linux/amd64 -e QEMU_CPU=max swift:latest swift build ``` -------------------------------- ### Install Swift Toolchain on Amazon Linux 2 Source: https://www.swift.org/documentation/server/guides/deploying/aws.html Installs the Swift toolchain and its dependencies on an Amazon Linux 2 instance. This is useful for compiling Swift code directly on the server. ```bash SwiftToolchainUrl="https://swift.org/builds/swift-5.4.1-release/amazonlinux2/swift-5.4.1-RELEASE/swift-5.4.1-RELEASE-amazonlinux2.tar.gz" sudo yum install ruby binutils gcc glibc-static gzip libbsd libcurl libedit libicu libsqlite libstdc++-static libuuid libxml2 tar tzdata ruby -y cd $(mktemp -d) wget ${SwiftToolchainUrl} -O swift.tar.gz gunzip < swift.tar.gz | sudo tar -C / -xv --strip-components 1 ``` -------------------------------- ### Build Project on Linux with Swift 3.0 Toolchain Source: https://www.swift.org/documentation/source-compatibility Commands to download and use the Swift 3.0 release toolchain on Linux to build a project. This is useful for testing compatibility on a Linux environment. ```bash curl -O https://download.swift.org/swift-3.0-release/ubuntu1510/swift-3.0-RELEASE/swift-3.0-RELEASE-ubuntu15.10.tar.gz tar xzvf swift-3.0-RELEASE-ubuntu15.10.tar.gz ./check project-path-field --swiftc swift-3.0-RELEASE-ubuntu15.10/usr/bin/swiftc ``` -------------------------------- ### Name According to Role: Basic Example Source: https://www.swift.org/documentation/api-design-guidelines Name variables and parameters according to their roles rather than their type constraints. This example shows changing 'string' to 'greeting' and 'widgetFactory' to 'supplier'. ```swift var **string** = "Hello" protocol ViewController { associatedtype **View**Type : View } class ProductionLine { func restock(from **widgetFactory**: WidgetFactory) } ``` ```swift var **greeting** = "Hello" protocol ViewController { associatedtype **ContentView** : View } class ProductionLine { func restock(from **supplier**: WidgetFactory) } ``` -------------------------------- ### Install perf User Probes on Allocation Functions Source: https://www.swift.org/documentation/server/guides/allocations.html Installs perf user probes on the `malloc`, `calloc`, and `posix_memalign` functions in libc. This allows `perf` to track when these allocation functions are called. ```bash # figures out the path to libc libc_path=$(readlink -e /lib64/libc.so.6 /lib/x86_64-linux-gnu/libc.so.6) # delete all existing user probes on libc (instead of * you can also list them individually) perf probe --del 'probe_libc:*' # installs a probe on `malloc`, `calloc`, and `posix_memalign` perf probe -x "$libc_path" --add malloc --add calloc --add posix_memalign ``` -------------------------------- ### Install and configure spaceline for status bar theme Source: https://www.swift.org/documentation/articles/zero-to-swift-emacs.html Installs the `spaceline` package and applies the `spaceline-emacs-theme`. This is an alternative or complementary package for customizing the Emacs status bar, often used with Powerline. ```emacs-lisp ;; Spaceline (use-package spaceline :ensure t :after powerline :config (spaceline-emacs-theme)) ``` -------------------------------- ### Initialize Copilot Environment Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Create a new environment for your Copilot application, such as 'dev', 'test', or 'prod'. This aligns with deployment phases. ```bash copilot env init --name dev --app todo --default-config ``` -------------------------------- ### Build and Package Swift App with Distroless Source: https://www.swift.org/documentation/server/guides/packaging.html This Dockerfile demonstrates packaging a Swift application using a Distroless C++ base image. It uses a multi-stage build similar to the standard Docker approach but targets a minimal runtime environment. ```dockerfile #------- build ------- # Building using Ubuntu Bionic since its compatible with Debian runtime FROM swift:bionic as builder # set up the workspace RUN mkdir /workspace WORKDIR /workspace # copy the source to the docker image COPY . /workspace RUN swift build -c release --static-swift-stdlib #------- package ------- # Running on distroless C++ since it includes # all(*) the runtime dependencies Swift programs need FROM gcr.io/distroless/cc-debian10 # copy executables COPY --from=builder /workspace/.build/release/ / # set the entry point (application name) CMD [""] ``` -------------------------------- ### Initialize Vapor Project Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Initializes a new Vapor project named 'api' without interactive prompts. This command sets up the basic structure for your Vapor application. ```bash vapor new api -n ``` -------------------------------- ### Demangle Symbols with addr2line and swift demangle Source: https://www.swift.org/documentation/server/guides/memory-leaks-and-usage.html Use addr2line to get symbol information from an executable and pipe the output to 'swift demangle' to get human-readable function names for stack traces. ```bash # /tmp/test+0xc62ce addr2line -e /tmp/test -a 0xc62ce -ipf | swift demangle ``` -------------------------------- ### Show Release Build Binary Path Source: https://www.swift.org/documentation/server/guides/building.html Display the full path to the release build binary artifact. This helps in locating deployable binaries. ```bash swift build --show-bin-path -c release ``` -------------------------------- ### Create Addon Configuration File Source: https://www.swift.org/documentation/server/guides/deploying/aws-copilot-fargate-vapor-mongo.html Creates an empty CloudFormation YAML file for the API Gateway addon. ```bash touch copilot/api/addons/apigateway.yml ``` -------------------------------- ### Compensate for Weak Type Information: Clear Example Source: https://www.swift.org/documentation/api-design-guidelines Precede weakly typed parameters with a noun describing their role to restore clarity. This example refines the 'add' function signature and call site for better understanding. ```swift func add**Observer**(_ observer: NSObject, for**KeyPath** path: String) grid.addObserver(self, forKeyPath: graphics) // clear ``` -------------------------------- ### Compensate for Weak Type Information: Vague Example Source: https://www.swift.org/documentation/api-design-guidelines When parameter types are generic (e.g., NSObject, Any, String), context at the use site may be vague. This example shows a less clear 'add' function signature and call. ```swift func add(_ observer: NSObject, for keyPath: String) grid.add(self, for: graphics) // vague ``` -------------------------------- ### Initialize lazy.nvim Plugin Manager Source: https://www.swift.org/documentation/articles/zero-to-swift-nvim.html This Lua script initializes the lazy.nvim plugin manager. It clones the repository if it doesn't exist and sets up the plugin configuration. ```lua -- init.lua local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim" if not (vim.uv or vim.loop).fs_stat(lazypath) then local lazyrepo = "https://github.com/folke/lazy.nvim.git" local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath }) if vim.v.shell_error ~= 0 then vim.api.nvim_echo({ { "Failed to clone lazy.nvim:\n", "ErrorMsg" }, { out, "WarningMsg" }, { "\nPress any key to exit..." }, }, true, {}) vim.fn.getchar() os.exit(1) end end vim.opt.rtp:prepend(lazypath) require("lazy").setup("plugins", { ui = { icons = { cmd = "", config = "", event = "", ft = "", init = "", keys = "", plugin = "", runtime = "", require = "", source = "", start = "", task = "", lazy = "", }, }, }) require("config.lsp") vim.opt.wildmenu = true vim.opt.wildmode = "list:longest,list:full" -- don't insert, show options -- line numbers vim.opt.nu = true vim.opt.rnu = true -- textwrap at 80 cols vim.opt.tw = 80 -- set solarized colorscheme. -- NOTE: Uncomment this if you have installed solarized, otherwise you'll see -- errors. -- vim.cmd.background = "dark" -- vim.cmd.colorscheme("solarized") -- vim.api.nvim_set_hl(0, "NormalFloat", { bg = "none" }) ``` -------------------------------- ### Build Statically Linked Linux Binary (ARM64) Source: https://www.swift.org/documentation/articles/static-linux-getting-started.html Builds a statically linked executable for the ARM64 Linux architecture using the specified Swift SDK. ```bash $ swift build --swift-sdk aarch64-swift-linux-musl Building for debugging... [8/8] Linking hello Build complete! (2.00s) $ file .build/aarch64-swift-linux-musl/debug/hello .build/aarch64-swift-linux-musl/debug/hello: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, with debug_info, not stripped ``` -------------------------------- ### Remove Installed SDK Source: https://www.swift.org/documentation/articles/static-linux-getting-started.html Removes a specified Static Linux SDK from the system. ```bash $ swift sdk remove ``` -------------------------------- ### Function Signature with Awkward Parameter Names Source: https://www.swift.org/documentation/api-design-guidelines Shows examples of parameter names that lead to awkward or ungrammatical documentation. ```swift /// Return an `Array` containing the elements of `self` /// that satisfy `**includedInResult**`. func filter(_ **includedInResult**: (Element) -> Bool) -> [Generator.Element] /// Replace the **range of elements indicated by `r`** with /// the contents of `**with**`. mutating func replaceRange(_ **r**: Range, **with**: [E]) ```