Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

SwiftCodeBook

A comprehensive Swift utility library and learning resource for Apple platform development.

Stars
Swift 6.0PlatformsXcode 26+License

English | 中文


What is SwiftCodeBook?

SwiftCodeBook is a Swift utility library and educational reference for Apple platform development. It provides 50 production-ready extensions and utility classes alongside 24 educational examples — all built with zero external dependencies, using only Apple's native frameworks.

The project is organized into three parts:

  • Tools — 50 reusable files: type extensions for Foundation, UIKit, and SwiftUI, plus standalone utility classes for concurrency, hashing, caching, animation, and more.
  • UseCase — 24 self-contained educational examples covering concurrency patterns, memory management, Combine, property wrappers, KVO, UIKit techniques, and SwiftUI patterns.
  • Note.swift — A curated bilingual (Chinese/English) reference of real-world development pitfalls and best practices.
Foundation Extensions — 24 files
ExtensionHighlights
Array+ToolsSafe subscript, JSON conversion, plist loading, duplicate removal
AttributedString+ToolsAttributedString manipulation utilities
BinaryFloatingPoint+ToolsFloating-point comparison and formatting
CGSize+ToolsCGSize arithmetic and transformation
Character+ToolsCharacter classification and conversion
Data+ToolsData manipulation and conversion
Date+ToolsCalendar components, date arithmetic, comparisons
DateFormatter+ToolsPreconfigured DateFormatter instances
Dictionary+ToolsJSON serialization, plist file loading
DispatchQueue+ToolsDispatch queue convenience methods
Duration+ToolsDuration formatting and conversion
FileManager+ToolsPath shortcuts (documents, cache, tmp), concurrent file size calculation
ISO8601DateFormatter+ToolsISO 8601 date formatting
JSONCoder+ToolsJSONEncoder/JSONDecoder configuration helpers
Locale+ToolsLocale detection and formatting
NSAttributedString+ToolsNSAttributedString creation and manipulation
NSNumber+ToolsNSNumber type conversion
NSRange+ToolsNSRange validation and conversion
NSString+ToolsNSString bridging utilities
Publisher+ToolsCombine publisher operators and helpers
Result+ToolsResult type convenience methods
String+ToolsRange conversion (NSRange ↔ Range), language direction detection
Task+ToolsTask-to-AnyCancellable bridge, structured concurrency helpers
URL+ToolsQuery dictionary parsing, query item manipulation
UIKit Extensions — 7 files
ExtensionHighlights
UIBezierPath+ToolsBezier path construction helpers
UIColor+ToolsHex string parsing, RGBA extraction, hex generation
UIFont+ToolsFont creation and system font utilities
UIImage+ToolsColor-based creation, orientation fix, SF Symbol initialization
UIStackView+ToolsStack view configuration shortcuts
UIView+ToolsView hierarchy and layout helpers
UIViewController+ToolsView controller presentation utilities
SwiftUI Extensions — 2 files
ExtensionHighlights
View+Toolsmodify(), onSizeChange(), onSafeAreaInsetsChange(), onWindowSizeChange(), onInterfaceOrientationChange()
Spacer+ToolsSpacer convenience initializers
Foundation Utilities — 13 files
UtilityDescription
AESCryptoNative AES-GCM, CBC, ECB (interoperability only), CFB, CFB8, CTR, and OFB with type-safe mode parameters and secure key/IV generation
AnyJSONValueType-erased JSON value with Codable/Hashable conformance and safe accessors
AsyncSemaphoreActor-based async/await semaphore
CancelBagThread-safe Combine subscription management via OSAllocatedUnfairLock
CurrentApplicationApp metadata (name, version, build, bundle ID), key window, real-time memory usage
CurrentDeviceDevice info (model, OS version, disk space), simulator detection, device type classification
CurrentValuePublisherProtocol and type-erased wrapper for current-value publishers
HashHandlerMulti-algorithm hashing (MD5, SHA1, SHA256, SHA384, SHA512) with 64 KB streaming
MemoryCacheType-safe NSCache wrapper with automatic cleanup on memory warnings
SendablePassthroughSubjectThread-safe Combine PassthroughSubject using NSRecursiveLock
SerialTaskExecutorAsyncStream-based serial task queue with guaranteed execution order
WeakObjectGeneric weak reference wrapper for AnyObject types
XMLNodeParserRecursive XML node parsing with dictionary output
UIKit Utilities — 5 files
UtilityDescription
CADisplayLinkAnimatorDuration-based animator with cubic Bezier timing and configurable frame rate
CADisplayLinkTimerDisplay link-based timer with elapsed time tracking
GradientViewUIView subclass backed by CAGradientLayer
LyricHighlightingLabelSingle-line label with progress-based text highlighting
UIInterfaceOrientationInterface orientation detection and conversion
Use Cases — 24 educational examples
TopicContent
ConcurrencyStructured concurrency, AsyncStream serial execution, Task scheduling, GCD
Memory & PointersPointer types, memory layout, unsafe operations, thread-safe lazy initialization
CombinePublisher patterns, subscription management
Property WrappersValue clamping (@Limit0To1, @LimitAToB), @UserDefaultWrapper
Associated ObjectsRuntime property storage for classes and protocols via OSAllocatedUnfairLock
KVOKey-Value Observing patterns and timing considerations
Enums & TypesEnum comparison, type switching, OptionSet usage
Hit Testing & TouchCustom hit test for out-of-bounds subviews, touch target expansion
Animation & LayoutAuto Layout constraint animation, shadow rendering optimization
Scroll & ViewsScroll state detection, content mode behavior, view lifecycle
Text & WebViewTappable text in UITextView, zoom-disabled WKWebView
SwiftUINSAttributedString to SwiftUI conversion
Development Notes — Note.swift

A bilingual (Chinese/English) reference of real-world iOS/macOS development pitfalls covering:

Signed/unsigned number edge cases, floating-point traps (NaN, Infinity), file system case sensitivity (simulator vs. device), memory management in dealloc, UIControl vs. Cell selected state conflicts, SwiftUI view refresh optimization, Combine publisher timing quirks (@Published vs. CurrentValueSubject), lock usage with async/await, integer version comparison, and more.

Features

  • Swift 6.0 Strict Concurrency — Full async/await, actors, and Sendable conformance throughout
  • Thread-Safe by Design — Uses actors, OSAllocatedUnfairLock, and NSRecursiveLock for safe concurrent access
  • Multi-Platform — iOS, macOS, tvOS, watchOS, and visionOS with platform-aware conditional compilation (#if os(...), #if canImport(...))
  • Zero Dependencies — Built entirely on Apple's native frameworks: Foundation, UIKit, SwiftUI, Combine, CryptoKit, QuartzCore
  • Bilingual Documentation — Code comments and development notes in both Chinese and English

Development

Building is only supported on macOS.

Prerequisites

RequirementMinimum Version
macOS15.6+ (Sequoia)
Xcode26+

Build Steps

# 1. Clone the repository
git clone https://github.com/yuman07/SwiftCodeBook.git
# 2. Navigate to the project directorycd SwiftCodeBook
# 3. Open the project in Xcode
open SwiftCodeBook.xcodeproj
# 4. Select a target scheme and simulator, then build (⌘B) or run (⌘R)

Technical Overview

SwiftCodeBook follows a two-layer architecture separating reusable tools from educational examples, with platform-aware conditional compilation across five Apple platforms.

The Tools layer is split into two categories: Extensions add capabilities to existing Apple framework types (Foundation, UIKit, SwiftUI), while Utility Classes are standalone components for concurrency, hashing, caching, and UI animation. The UseCase layer contains self-contained educational examples that demonstrate patterns and techniques — each file focuses on a single topic and can be understood independently.

The concurrency model is a key design highlight. Rather than a one-size-fits-all approach, the project demonstrates multiple thread-safety strategies matched to their use cases:

  • Actors power AsyncSemaphore — leveraging Swift's built-in isolation for clean async coordination
  • OSAllocatedUnfairLock protects CancelBag and AssociatedObject — minimal-overhead locking for simple mutable state
  • NSRecursiveLock wraps SendablePassthroughSubject — reentrant safety when bridging Combine subjects to Sendable
  • AsyncStream drives SerialTaskExecutor — guaranteeing serial execution order through stream-based task queuing

HashHandler uses CryptoKit with a streaming API that processes data in 64 KB chunks, keeping memory constant regardless of file size. MemoryCache wraps NSCache with type safety and subscribes to memory warning publishers from CurrentApplication for automatic cleanup. CADisplayLinkAnimator implements a full animation system with cubic Bezier timing functions parsed from CAMediaTimingFunction control points.

Tech Stack

CategoryTechnologies
LanguageSwift 6.0 (strict concurrency mode)
UI FrameworksSwiftUI, UIKit, AppKit, WatchKit
ReactiveCombine
CryptographyCryptoKit
AnimationQuartzCore (CADisplayLink, CAGradientLayer)
Concurrencyasync/await, Actor, AsyncStream, OSAllocatedUnfairLock
PlatformsiOS 26+, macOS 26+, tvOS 26+, watchOS 26+, visionOS 26+
Build ToolXcode 26+

Architecture

graph TD
subgraph Tools["Tools — Reusable Code"]
FndExt["Foundation Extensions<br/>Array · String · URL · Date ..."]
UIKExt["UIKit Extensions<br/>UIColor · UIImage · UIView ..."]
SUIExt["SwiftUI Extensions<br/>View · Spacer"]
FndUtil["Foundation Utilities<br/>AsyncSemaphore · HashHandler<br/>SerialTaskExecutor · MemoryCache ..."]
UIUtil["UIKit Utilities<br/>CADisplayLinkAnimator<br/>GradientView · LyricLabel"]
end
subgraph UseCase["UseCase — Educational Examples"]
FndUC["Foundation Patterns<br/>Concurrency · Memory · Combine"]
UIKUC["UIKit Patterns<br/>HitTest · HotZone · Shadow"]
SUIUC["SwiftUI Patterns"]
end
subgraph Frameworks["Apple Frameworks (Zero External Dependencies)"]
Fnd["Foundation · Combine"]
UK["UIKit · QuartzCore"]
SU["SwiftUI"]
CK["CryptoKit"]
end
FndExt -->|"extends"| Fnd
FndUtil -->|"Actor · AsyncStream"| Fnd
FndUtil -->|"streaming hash"| CK
UIKExt -->|"extends"| UK
UIUtil -->|"CADisplayLink"| UK
SUIExt -->|"extends"| SU
FndUC -.->|"demonstrates"| FndUtil
FndUC -.->|"demonstrates"| FndExt
UIKUC -.->|"demonstrates"| UIKExt
SUIUC -.->|"demonstrates"| SUIExt
Loading
  • Tools to Frameworks (solid arrows) — Extensions directly extend types from Apple frameworks; Foundation Utilities use Actor isolation and AsyncStream from the Swift runtime, while HashHandler streams through CryptoKit; UIKit Utilities leverage CADisplayLink for frame-synchronized animation
  • UseCase to Tools (dashed arrows) — Educational examples demonstrate patterns found in the Tools layer; Foundation use cases cover both utility classes (e.g., SerialTaskExecutor concurrency patterns) and extension techniques (e.g., pointer and memory operations)
  • Zero External Dependencies — Every arrow terminates at an Apple framework, confirming the project relies entirely on the native platform SDK

Project Structure

SwiftCodeBook/
|-- SwiftCodeBookApp.swift # SwiftUI app entry point
|-- Watch Watch App/
| |-- WatchApp.swift # watchOS app entry point
| `-- ContentView.swift # watchOS main view
`-- Source/
|-- Note.swift # Development pitfalls (bilingual)
|-- Tools/
| |-- Extension/
| | |-- Foundation/ # 24 Foundation type extensions
| | |-- UIKit/ # 7 UIKit type extensions
| | `-- SwiftUI/ # 2 SwiftUI type extensions
| |-- Foundation/ # 12 standalone utility classes
| `-- UIKit/ # 5 UIKit utility classes
`-- UseCase/
|-- Foundation/ # 13 Foundation pattern examples
|-- UIKit/ # 10 UIKit pattern examples
`-- SwiftUI/ # 1 SwiftUI pattern example

License

This project is licensed under the MIT License.

About

A comprehensive Swift utility library for Apple platforms. 一个全面的 Swift 工具库,面向 Apple 全平台开发。

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages