SwiftBites

This section contains some short posts or annotated code snippets that albeit interesting or likely useful didn't warrant a complete blog article.

All these examples and posts are compatible with Swift 3.

#97: When to Use final in Swift
Use final when a class or member is not designed for subclassing or overriding.

#96: Dynamic Member Lookup in Swift
@dynamicMemberLookup lets a type forward unknown member access to some underlying storage.

#95: Key Paths in Swift
Key paths let you pass references to properties around as values.

#94: @autoclosure in Swift APIs
@autoclosure gives you lazy evaluation without making the call site look like a closure call.

#93: Sendable in Swift
Sendable marks values that are safe to transfer across concurrency boundaries.

#92: nonisolated in Swift
Mark actor members as nonisolated when they do not touch isolated state and do not need await.

#91: Actors in Swift
Actors protect mutable shared state by isolating access behind async boundaries.

#90: Task Groups in Swift
Task groups are the structured concurrency tool for fan-out parallel work.

#89: async let in Swift
Run a few child async operations in parallel with very little syntax.

#88: @MainActor in Swift
Use @MainActor to state clearly that code must run on the main actor, usually for UI work.

#87: @available and Deprecation in Swift
Mark APIs by platform and version, and guide callers toward replacements.

#86: @discardableResult in Swift
Allow callers to ignore a return value intentionally without triggering warnings.

#85: typealias for Readability in Swift
typealias can make closures, tuples and generic-heavy signatures much easier to scan.

#84: Nested Types in Swift
Keep helper enums and structs close to the type that actually owns them.

#83: Custom Subscripts in Swift
Subscripts are not limited to arrays and dictionaries; your own types can define them too.

#82: Partial Ranges in Swift
Partial ranges are a compact way to slice collections from, to or through a boundary.

#81: Half-Open vs Closed Ranges in Swift
Use ..< for exclusive upper bounds and ... when the final value should be included.

#80: stride in Swift
Iterate numeric ranges by custom steps instead of counting only by one.

#79: zip with Swift Sequences
Pair elements from two sequences without manual indexing.

#78: allSatisfy in Swift
Check whether every element in a sequence matches a condition with a very readable API.

#77: reduce(into:) in Swift
Use reduce(into:) when building a mutable result to avoid unnecessary copying.

#76: compactMapValues for Dictionaries
Remove nil values from a dictionary transformation in one pass.

#75: map vs flatMap vs compactMap
These three look similar, but they solve different transformation problems.

#74: Optional Chaining in Swift
Optional chaining works on properties, methods and subscripts, not just simple field access.

#73: try?, try! and do/catch in Swift
Swift gives you three main ways to handle throwing calls depending on how much control you need.

#72: Custom Errors with LocalizedError
Use LocalizedError to provide user-facing descriptions and recovery hints.

#71: Result in Swift
Model success and failure explicitly with Result instead of separate optionals and errors.

#70: some vs any in Swift
some keeps one hidden concrete type, while any stores values of potentially different concrete types.

#69: Protocol Extension Dispatch Gotchas
Methods declared only in protocol extensions are not dynamically dispatched through the protocol type.

#68: Default Implementations in Protocol Extensions
Protocol extensions can provide shared behavior without inheritance.

#67: Constrained Extensions in Swift
Extend generic types only for the cases where a specific constraint holds.

#66: where Clauses in Swift Generics
Use where to express precise generic constraints without bloating the main signature.

#65: Conditional Conformance in Swift
Make a generic type conform to a protocol only when its generic parameter also conforms.

#64: Associated Types in Swift Protocols
Associated types let protocols describe placeholder types chosen by each conforming type.

#63: Self in Protocols and Classes
Self refers to the conforming or dynamic type and is useful for fluent APIs and factory methods.

#62: Protocol Existentials with any in Swift
Use any when you want a value whose concrete type can vary at runtime.

#61: Opaque Return Types with some
Return a concrete type while exposing only the protocol it conforms to.

#60: Trailing Closures in Swift
Trailing closure syntax keeps callback-heavy APIs easier to read.

#59: Using unowned Safely in Swift
unowned avoids optional unwrapping, but only when the referenced object is guaranteed to outlive the user.

#58: Using [weak self] in Swift Closures
Capture self weakly in escaping closures when the closure should not keep the object alive.

#57: Capturing Values in Swift Closures
Closures remember the values and references they capture from the surrounding scope.

#56: Escaping Closures in Swift
A closure is escaping when it can outlive the function call that receives it.

#55: inout Parameters in Swift
Use inout when a function needs to modify the caller’s variable directly.

#54: Why mutating Exists in Swift
Value types must mark methods as mutating when they change self or stored properties.

#53: Property Observers: willSet and didSet
React to value changes without writing a full custom setter.

#52: Computed Properties with get and set
Expose derived values cleanly without storing extra state.

#51: Lazy Stored Properties in Swift
Delay expensive initialization until the property is accessed for the first time.

#50: defer in Swift
Run cleanup code when the current scope exits, even if you return early or throw.

#49: Pattern Matching with guard case in Swift
Use guard case to unwrap the enum case you need and exit early otherwise.

#48: Pattern Matching with if case in Swift
Use if case when you only care about one enum pattern and do not need a full switch.

#47: Wait or Delay in Swift
Use asyncAfter for delayed work and avoid sleeping the main thread.

#46: Unexpectedly Found nil While Unwrapping an Optional
That crash means a force unwrap hit nil; safe unwrapping patterns avoid it completely.

#45: Get the Type of a Variable in Swift
Use type(of:) when you need the dynamic runtime type.

#44: Singletons without dispatch_once in Swift
A static let property is the modern thread-safe singleton pattern in Swift.

#43: Set Operations in Swift
union, intersection, subtracting and symmetricDifference cover the most common set math.

#42: Substrings in Swift 4 or Newer
String slices return Substring values that you can keep as slices or convert back to String.

#41: Struct or Class in Swift?
Prefer structs by default, then move to classes only when you need reference semantics or inheritance.

#40: String Length in Swift
Use count to get the number of characters in a Swift string.

#39: String Characters by Index in Swift
Strings are not integer-indexed, so use String.Index and offset calculations.

#38: Static vs Class Properties in Swift
Use static for non-overridable type members and class when subclasses should customize them.

#37: Shuffle Arrays in Swift
Use shuffled() for a copy or shuffle() for in-place randomization.

#36: Replace Character Occurrences in Swift 5
Use replacingOccurrences(of:with:) for the common whole-string replacement case.

#35: The #pragma mark Equivalent in Swift
Use // MARK:, // TODO: and // FIXME: to organize code in Xcode.

#34: Optional Methods in Protocols
Use @objc optional on Apple platforms, or prefer protocol extensions with default implementations.

#33: UserDefaults Subscripts in Swift
UserDefaults has typed getters, but a tiny subscript extension can still be convenient.

#32: List All Enum Cases in Swift 5
Conform to CaseIterable to get a collection of all enum cases.

#31: Join a String Array in Swift 4+
Use joined(separator:) to combine string arrays cleanly.

#30: Iteration with Index in Swift
Use enumerated() when you need both the element and its offset.

#29: Interesting Uses of @autoclosure
Use @autoclosure when you want lazy evaluation with a call-site that still looks simple.

#28: #if and Other #ifdef Replacements in Swift
Swift uses compile-time configuration blocks such as #if os, #if arch and custom flags.

#27: Dispatch After in Swift 5
Schedule delayed work with DispatchQueue.asyncAfter.

#26: Different Ways to Add Elements to an Array
append, append(contentsOf:), insert and += all solve slightly different problems.

#25: Convert URL to String in Swift
Use absoluteString when you need the full URL text representation.

#24: Convert String to Int in Swift
Use Int(value) and unwrap the optional safely.

#23: Convert Int to String in Swift
Create strings from integers with String(value) or string interpolation.

#22: Check if a String Contains Another String in Swift
Use contains or range(of:) depending on whether you need a boolean or the match location.

#21: Check if an Array Contains Elements in Swift
Use isEmpty instead of comparing the count manually.

#20: Calling Objective-C from Swift
Expose Objective-C headers to Swift with a bridging header and import the APIs normally.

#19: Validate Email Addresses in Swift
Use a lightweight regex for client-side checks, but let the server be the final authority.

#18: Background Threads in Swift
Run expensive work off the main queue and hop back to the UI queue when you are done.

#17: Generate Random Numbers with Swift
Random numbers with arc4random

#16: Singletons in Swift 3
How to write a singleton in Swift

#15: Rounding Floating Point Numbers to Specific Decimal Places
Rounding numbers to get the desired format.

#14: NSTimer with Swift 3
Using the Timer class with Swift 3

#13: KVO and KVC in Swift 3
Key-Value Observing/Coding from Obj-C to Swift.

#12: Rounding Floating Point Numbers in Swift 3
Rounding float and doubles the right way.

#11: Print object's content with dump
Debug using the dump method to see your object's content.

#10: Executing closures with a delay in Swift 3
Delayed execution with libDispatch.

#09: Creating DispatchQueues in Swift 3
GCD's Queues after the great rename.

#08: Merging Dictionaries in Swift
Extending dictionaries with merge methods.

#07: Labeled statements in Swift
Labeled statements in Swift, to jump to a specific outer loop.

#06: URL/URI Escaping in Swift 3: Encoding and Decoding
Escaping/encoding url or uri strings.

#05: Sorting Array and Dictionaries in Swift
A few examples on how to sort collections in Swift 3 with sorted(by:).

#04: Splitting Strings in Swift
Splitting strings in Swift with or without Foundation.

#03: String trimming in Swift 3
Trimming a string removing unwanted surrounding characters.

#02: CustomStringConvertible and Description in Swift
The NSObject description is now implemented with this protocol.

#01: Swapping variables in Swift
Swapping variables in Swift leveraging tuples.

I'm also on Twitter and GitHub.

Subscribe via RSS.