Skip to content

About

A handy collection of native Swift extensions to boost your productivity. Tested, documented with usage examples, and dependency-free, with a live catalog app to try every helper.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

11 stars

Watchers

1 watching

Forks

Repository files navigation

SwiftExtension app icon

SwiftExtension

Small, tested, dependency-free extensions for Foundation, UIKit and SwiftUI.
Add one Swift package. Browse every helper in a live catalog app.

CI CodeQL Swift versions Platforms Swift 6 strict concurrency Dependencies: none License MIT

Catalog home   Interactive bar chart example   Donut chart example

Contents

Why · Installation · Quick start · API · Catalog app · Animations · Concurrency and safety · Requirements · Documentation · Contributing · Project health · License

Why

  • One import, many small helpers. Each extension is independent and documented with an example. No framework to learn.
  • See it before you use it. A catalog app runs all 56 examples live. Every screen has a Play button and the exact code.
  • Production habits. Swift 6 language mode with strict concurrency, public API documented with DocC, 87% test coverage, warnings treated as errors in CI.
  • Accessible by default. Dynamic Type, VoiceOver and Reduce Motion are respected. State is never shown by color alone.
  • No dependencies. Only Apple frameworks.

Installation

Swift Package Manager

Xcode: File → Add Package Dependencies, then enter

https://github.com/ANSCoder/Swift-Extension

Package.swift:

dependencies: [
    .package(url: "https://github.com/ANSCoder/Swift-Extension", from: "2.0.0")
],
targets: [
    .target(name: "YourApp", dependencies: ["SwiftExtension"])
]

Then:

import SwiftExtension

Copy a single file

Every file in Sources/SwiftExtension works on its own. Copy only what you need, and add public if you share it across modules. ExString uses DateFormatter.posix from ExDate, and the SwiftUI view helpers use FirstAppearModifier and SizePreferenceKey.

Quick start

import SwiftExtension
import SwiftUI

struct ProfileView: View {
    @State private var email = ""
    @State private var errorMessage: String?
    @State private var isSaving = false

    var body: some View {
        Form {
            TextField("Email", text: $email)
            Label(email.isEmail ? "Valid" : "Invalid", systemImage: email.isEmail ? "checkmark.circle" : "xmark.circle")
                .hidden(if: email.isEmpty)
        }
        .loadingOverlay(isSaving)
        .errorAlert(message: $errorMessage)
        .dismissKeyboardOnTap()
    }
}

API

Foundation helpers build on every platform in the package. UIKit and SwiftUI helpers are compiled where UIKit exists.

Foundation

Type Helpers
String isEmail, isMobile, isAlphanumeric, isValidURL, initials, trim, trimLine, removeSpace, firstLetterCapitalized, truncated(to:), changeDate(_:)
Date toString(), toTimeString(), isToday, isSameDay(as:), startOfDay, adding(_:value:)
Array, Collection, Sequence atIndex(_:), chunked(into:), isNotEmpty, removingDuplicates(on:)
Comparable clamped(to:)
Double rounded(toPlaces:)
Optional<String> orEmpty
Encodable asDictionary()
URL queryItems, appendingQueryItems(_:)
Bundle appVersion, buildNumber

SwiftUI

Helper What it does
if(_:transform:), ifLet(_:transform:) Apply a modifier only when a condition holds or a value exists
hidden(if:) Hide a view and keep its layout space
onFirstAppear(perform:) Run once, ignoring later appearances
onSizeChange(perform:) Report the rendered size
loadingOverlay(_:) Dim, spinner, block taps
errorAlert(_:message:) OK alert bound to an optional message
dismissKeyboardOnTap() Resign first responder on tap. Unavailable in app extensions
cardStyle(cornerRadius:), roundedBorder(_:width:cornerRadius:) Card background and stroke
shake(trigger:) Wobble on change. Skipped when Reduce Motion is on
shimmer(_:), redactedShimmer(_:) Loading skeleton with a moving highlight
snapshot(scale:) Render a view into a UIImage
Color(hex:) #RRGGBB, RRGGBB or RRGGBBAA

UIKit

Type Helpers
UIColor init(hex:), hexString
UIView addSubviews(_:), pinToEdges(of:insets:) (right-to-left aware)
UILabel setLeft(), setRight(), underline(), attribute(_:effect:)
UIViewController showAlertView(title:message:), showAlertWithMessage(_:duration:with:)
UIScrollView scrollToView(view:animated:), scrollToTop(animated:), scrollToBottom(animated:)
UINavigationBar setTitleFont(_:color:), makeTransparent(withTint:), setColors(background:text:)
UITextField setBorderAndCorner(color:), setLeftPaddingPoints(_:), setRightPaddingPoints(_:), isValidEmail, isPhoneNumber
UIImage toBase64String, resized(by:), halfSizeImage, quarterhalfSizeImage
UIImageView setRounded(), setCornerRadius()
NSMutableAttributedString bold(_:size:), normal(_:)

Catalog app

Open Example/Swift-Extension.xcodeproj and run it. It uses the package from the repository root, so it always shows the real code.

Category Examples
Scroll (6) scroll to top/bottom, scroll to view, paging, scroll position, pinned headers, scroll transition
Keyboard (4) dismiss on tap, scroll dismisses, focus chain, keyboard toolbar
Stacks & Layout (5) alignment, Grid, adaptive grid, ViewThatFits, custom FlowLayout
Text (4) Markdown & AttributedString, Dynamic Type scaling, numeric transition, date styles
Animations (20) spring, implicit, transitions, matched geometry, PhaseAnimator, KeyframeAnimator, symbol effects, shake, drag spring, TimelineView, shimmer, confetti, radar pulse, draw-on checkmark, liquid wave, progress ring, card stack, aurora gradient, sliding segments, 3D tilt
Charts (6) interactive bars, line & area, donut with selection, stacked bars (absolute / 100%), scrollable time series, KPI cards with sparklines
View Modifiers (6) card style, conditional modifiers, loading overlay, error alert, size & first appear, view to image
Foundation (5) validation, date helpers, string helpers, number helpers, URL & Bundle helpers

Animations

Recorded from the catalog app. Every one is plain SwiftUI. The code is on its example screen.

Spring
Spring
Matched geometry
Matched geometry
Phase animator
Phase animator
Keyframes
Keyframes
SF Symbol effects
SF Symbol effects
Shake on error
Shake on error
Confetti burst
Confetti burst
Radar pulse
Radar pulse
Draw-on checkmark
Draw-on checkmark
Liquid wave gauge
Liquid wave gauge
Progress ring
Progress ring
Aurora gradient
Aurora gradient
Sliding segments
Sliding segments
Skeleton shimmer
Skeleton shimmer
3D tilt card
3D tilt card
Line & area chart
Line & area chart
Donut chart
Donut chart

Concurrency and safety

The package builds in Swift 6 language mode with complete strict concurrency checking, and CI treats warnings as errors.

  • No @unchecked Sendable, nonisolated(unsafe), @preconcurrency, locks or semaphores.
  • Date.toString() and toTimeString() use value-type FormatStyles, so there is no shared DateFormatter.
  • UIViewController.showAlertWithMessage waits with a main-actor Task, not a dispatch timer.
  • UIKit and SwiftUI helpers run on the main actor. Foundation helpers are plain value-type code.
  • No force unwraps or try! in library code. Inputs at boundaries return nil, false or an empty value instead of crashing.
  • UIKit and SwiftUI code sits inside #if canImport(UIKit), so swift build works on macOS.

Requirements

Swift 6.0 or later (Swift 6 language mode)
Xcode 16 or later. CI runs the latest stable Xcode
iOS 17.0+ (all helpers)
macOS 14.0+ (Foundation helpers only)
Dependencies None. The catalog's Charts examples use Apple's Swift Charts

Documentation

  • API reference built with DocC. Preview it in Xcode with Product → Build Documentation. It is hosted by the Swift Package Index once the package is listed.
  • Every public declaration has a /// comment with a usage example.
  • CHANGELOG · Maintaining

Development

swift build                      # Foundation helpers on the macOS host
swift test                       # Foundation tests on the macOS host

xcodebuild test -scheme SwiftExtension \
  -destination 'platform=iOS Simulator,name=iPhone 17'      # everything, on a simulator

xcrun swift-format lint --strict --recursive Sources Tests   # style

Add an example to the catalog

  1. Create Example/Swift-Extension/Catalog/Demos/<Category>/MyDemo.swift with a view that takes play: Int and a static let info = ExampleInfo(...).
  2. Add a case to Example/Swift-Extension/Catalog/Core/Example.swift and fill in its three switches: info, playHint and demo.
  3. Run the example tests. CatalogTests fails if a title, summary, code or hint is missing, or if titles repeat.

Recording the GIFs

The catalog has two launch arguments for documentation:

xcrun simctl launch booted anscoder.Swift-Extension -example confetti   # bare auto-playing stage
xcrun simctl launch booted anscoder.Swift-Extension -detail barChart    # one example screen

Record with xcrun simctl io booted recordVideo, then crop the stage and convert to GIF.

Contributing

Issues and pull requests are welcome. Read CONTRIBUTING.md first. By taking part you agree to the Code of Conduct. Report security problems privately, see SECURITY.md.

Project health

CI Format, macOS build and tests, iOS simulator tests with coverage, example app, DocC build. One required check: CI success
Security CodeQL for Swift on every PR and weekly. Dependabot for GitHub Actions and Swift packages
Review bots Danger PR checks, CodeRabbit and GitHub Copilot review (instructions), auto-labeling, release drafting
Releases Semantic versioning. Pushing a tag like 1.0.0 runs the tests and publishes a GitHub release

Migrating from the Swift 4 version

  • Minimum is now iOS 17 and Swift 6. Add the package instead of copying files.
  • changeDate(_:) and UIImage.toBase64String return optionals instead of crashing.
  • UINavigationBar helpers use UINavigationBarAppearance. The default title color is .label.
  • showAleartViewwithTitle and setCornerRadious still work but are deprecated.
  • ExFunction is now an enum namespace. Its static methods are unchanged.

License

MIT. See LICENSE.

Animation topics were inspired by awesome-ios-animation and awesome-swift.

About

A handy collection of native Swift extensions to boost your productivity. Tested, documented with usage examples, and dependency-free, with a live catalog app to try every helper.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

11 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages