{"id":13465270,"url":"https://github.com/JohnSundell/SwiftTips","last_synced_at":"2025-03-25T16:31:33.593Z","repository":{"id":37334611,"uuid":"79901724","full_name":"JohnSundell/SwiftTips","owner":"JohnSundell","description":"A collection of Swift tips \u0026 tricks that I've shared on Twitter","archived":false,"fork":false,"pushed_at":"2023-11-22T03:10:52.000Z","size":173,"stargazers_count":4018,"open_issues_count":1,"forks_count":246,"subscribers_count":413,"default_branch":"master","last_synced_at":"2025-03-16T10:08:44.436Z","etag":null,"topics":["swift","tips-and-tricks"],"latest_commit_sha":null,"homepage":"https://twitter.com/johnsundell","language":null,"has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohnSundell.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-01-24T10:34:29.000Z","updated_at":"2025-03-01T16:11:31.000Z","dependencies_parsed_at":"2024-01-08T10:16:56.867Z","dependency_job_id":"a36a1ab3-1461-46fc-ad61-b3e90f0fbc33","html_url":"https://github.com/JohnSundell/SwiftTips","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FSwiftTips","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FSwiftTips/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FSwiftTips/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnSundell%2FSwiftTips/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohnSundell","download_url":"https://codeload.github.com/JohnSundell/SwiftTips/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245090875,"owners_count":20559298,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["swift","tips-and-tricks"],"created_at":"2024-07-31T15:00:25.432Z","updated_at":"2025-03-25T16:31:33.573Z","avatar_url":"https://github.com/JohnSundell.png","language":null,"readme":"⚠️ **This list is no longer being updated. For my latest Swift tips, checkout the [\"Tips\" section on Swift by Sundell](https://www.swiftbysundell.com/tips)**.\n\n# Swift tips \u0026 tricks ⚡️\n\nOne of the things I really love about Swift is how I keep finding interesting ways to use it in various situations, and when I do - I usually share them on [Twitter](https://twitter.com/johnsundell). Here's a collection of all the tips \u0026 tricks that I've shared so far. Each entry has a link to the original tweet, if you want to respond with some feedback or question, which is always super welcome! 🚀\n\n**Also make sure to check out all of my other Swift content:**\n\n- 📖 [My weekly articles, with a new post about Swift every Sunday!](https://swiftbysundell.com)\n- 🎧 [My podcast which features special guests from around the community.](https://swiftbysundell.com/podcast)\n- 📬 [My monthly newsletter - rounding up all of my content, including these tips, on the 1st of every month.](https://swiftbysundell.com/newsletter)\n\n## Table of contents\n\n[#102 Making async tests faster and more stable](https://github.com/johnsundell/swifttips#102-making-async-tests-faster-and-more-stable)  \n[#101 Adding support for Apple Pencil double-taps](https://github.com/johnsundell/swifttips#101-adding-support-for-apple-pencil-double-taps)  \n[#100 Combining values with functions](https://github.com/johnsundell/swifttips#100-combining-values-with-functions)  \n[#99 Dependency injection using functions](https://github.com/johnsundell/swifttips#99-dependency-injection-using-functions)  \n[#98 Using a custom exception handler](https://github.com/johnsundell/swifttips#98-using-a-custom-exception-handler)  \n[#97 Using type aliases to give semantic meaning to primitives](https://github.com/johnsundell/swifttips#97-using-type-aliases-to-give-semantic-meaning-to-primitives)  \n[#96 Specializing protocols using constraints](https://github.com/johnsundell/swifttips#96-specializing-protocols-using-constraints)  \n[#95 Unwrapping an optional or throwing an error](https://github.com/johnsundell/swifttips#95-unwrapping-an-optional-or-throwing-an-error)  \n[#94 Testing code that uses static APIs](https://github.com/johnsundell/swifttips#94-testing-code-that-uses-static-apis)  \n[#93 Matching multiple enum cases with associated values](https://github.com/johnsundell/swifttips#93-matching-multiple-enum-cases-with-associated-values)  \n[#92 Multiline string literals](https://github.com/johnsundell/swifttips#92-multiline-string-literals)  \n[#91 Reducing sequences](https://github.com/johnsundell/swifttips#91-reducing-sequences)  \n[#90 Avoiding manual Codable implementations](https://github.com/johnsundell/swifttips#90-avoiding-manual-codable-implementations)  \n[#89 Using feature flags instead of feature branches](https://github.com/johnsundell/swifttips#89-using-feature-flags-instead-of-feature-branches)  \n[#88 Lightweight data hierarchies using tuples](https://github.com/johnsundell/swifttips#88-lightweight-data-hierarchies-using-tuples)  \n[#87 The rule of threes](https://github.com/johnsundell/swifttips#87-the-rule-of-threes)  \n[#86 Useful Codable extensions](https://github.com/johnsundell/swifttips#86-useful-codable-extensions)  \n[#85 Using shared UserDefaults suites](https://github.com/johnsundell/swifttips#85-using-shared-userdefaults-suites)  \n[#84 Custom UIView backing layers](https://github.com/johnsundell/swifttips#84-custom-uiview-backing-layers)  \n[#83 Auto-Equatable enums with associated values](https://github.com/johnsundell/swifttips#83-auto-equatable-enums-with-associated-values)  \n[#82 Defaults for associated types](https://github.com/johnsundell/swifttips#82-defaults-for-associated-types)  \n[#81 Creating a dedicated identifier type](https://github.com/johnsundell/swifttips#81-creating-a-dedicated-identifier-type)  \n[#80 Assigning optional tuple members to variables](https://github.com/johnsundell/swifttips#80-assigning-optional-tuple-members-to-variables)  \n[#79 Struct convenience initializers](https://github.com/johnsundell/swifttips#79-struct-convenience-initializers)  \n[#78 Usages of throwing functions](https://github.com/johnsundell/swifttips#78-usages-of-throwing-functions)  \n[#77 Nested generic types](https://github.com/johnsundell/swifttips#77-nested-generic-types)  \n[#76 Equatable \u0026 Hashable structures](https://github.com/johnsundell/swifttips#76-equatable-hashable-structures)  \n[#75 Conditional conformances](https://github.com/johnsundell/swifttips#75-conditional-conformances)  \n[#74 Generic type aliases](https://github.com/johnsundell/swifttips#74-generic-type-aliases)  \n[#73 Parsing command line arguments using UserDefaults](https://github.com/johnsundell/swifttips#73-parsing-command-line-arguments-using-userdefaults)  \n[#72 Using the \u0026 operator](https://github.com/johnsundell/swifttips#72-using-the--operator)  \n[#71 Capturing multiple values in mocks](https://github.com/johnsundell/swifttips#71-capturing-multiple-values-in-mocks)  \n[#70 Reducing the need for mocks](https://github.com/johnsundell/swifttips#70-reducing-the-need-for-mocks)  \n[#69 Using \"then\" as an external parameter label for closures](https://github.com/johnsundell/swifttips#69-using-then-as-an-external-parameter-label-for-closures)  \n[#68 Combining lazily evaluated sequences with the builder pattern](https://github.com/johnsundell/swifttips#68-combining-lazily-evaluated-sequences-with-the-builder-pattern)  \n[#67 Faster \u0026 more stable UI tests](https://github.com/johnsundell/swifttips#67-faster--more-stable-ui-tests)  \n[#66 Accessing the clipboard from a Swift script](https://github.com/johnsundell/swifttips#66-accessing-the-clipboard-from-a-swift-script)  \n[#65 Using tuples for view state](https://github.com/johnsundell/swifttips#65-using-tuples-for-view-state)  \n[#64 Throwing tests and LocalizedError](https://github.com/johnsundell/swifttips#64-throwing-tests-and-localizederror)  \n[#63 The difference between static and class properties](https://github.com/johnsundell/swifttips#63-the-difference-between-static-and-class-properties)  \n[#62 Creating extensions with static factory methods](https://github.com/johnsundell/swifttips#62-creating-extensions-with-static-factory-methods)  \n[#61 Child view controller auto-resizing](https://github.com/johnsundell/swifttips#61-child-view-controller-auto-resizing)  \n[#60 Using zip](https://github.com/johnsundell/swifttips#60-using-zip)  \n[#59 Defining custom option sets](https://github.com/johnsundell/swifttips#59-defining-custom-option-sets)  \n[#58 Using the where clause with associated types](https://github.com/johnsundell/swifttips#58-using-the-where-clause-with-associated-types)  \n[#57 Using first class functions when iterating over a dictionary](https://github.com/johnsundell/swifttips#57-using-first-class-functions-when-iterating-over-a-dictionary)  \n[#56 Calling instance methods as static functions](https://github.com/johnsundell/swifttips#56-calling-instance-methods-as-static-functions)  \n[#55 Dropping suffixes from method names to support multiple arguments](https://github.com/johnsundell/swifttips#55-dropping-suffixes-from-method-names-to-support-multiple-arguments)  \n[#54 Constraining protocols to classes to ensure mutability](https://github.com/johnsundell/swifttips#54-constraining-protocols-to-classes-to-ensure-mutability)  \n[#53 String-based enums in string interpolation](https://github.com/johnsundell/swifttips#53-string-based-enums-in-string-interpolation)  \n[#52 Expressively comparing a value with a list of candidates](https://github.com/johnsundell/swifttips#52-expressively-comparing-a-value-with-a-list-of-candidates)  \n[#51 UIView bounds and transforms](https://github.com/johnsundell/swifttips#51-uiview-bounds-and-transforms)  \n[#50 UIKit default arguments](https://github.com/johnsundell/swifttips#50-uikit-default-arguments)  \n[#49 Avoiding Massive View Controllers](https://github.com/johnsundell/swifttips#49-avoiding-massive-view-controllers)  \n[#48 Extending optionals](https://github.com/johnsundell/swifttips#48-extending-optionals)  \n[#47 Using where with for-loops](https://github.com/johnsundell/swifttips#47-using-where-with-for-loops)   \n[#46 Variable shadowing](https://github.com/JohnSundell/SwiftTips#46-variable-shadowing)   \n[#45 Using dot syntax for static properties and initializers](https://github.com/JohnSundell/SwiftTips#45-using-dot-syntax-for-static-properties-and-initializers)   \n[#44 Calling functions as closures with a tuple as parameters](https://github.com/JohnSundell/SwiftTips#44-calling-functions-as-closures-with-a-tuple-as-parameters)   \n[#43 Enabling static dependency injection](https://github.com/JohnSundell/SwiftTips#43-enabling-static-dependency-injection)   \n[#42 Type inference for lazy properties in Swift 4](https://github.com/JohnSundell/SwiftTips#42-type-inference-for-lazy-properties-in-swift-4)   \n[#41 Converting Swift errors to NSError](https://github.com/JohnSundell/SwiftTips#41-converting-swift-errors-to-nserror)   \n[#40 Making UIImage macOS compatible](https://github.com/JohnSundell/SwiftTips#40-making-uiimage-macos-compatible)   \n[#39 Internally mutable protocol-oriented APIs](https://github.com/JohnSundell/SwiftTips#39-internally-mutable-protocol-oriented-apis)   \n[#38 Switching on a set](https://github.com/JohnSundell/SwiftTips#38-switching-on-a-set)   \n[#37 Adding the current locale to cache keys](https://github.com/JohnSundell/SwiftTips#37-adding-the-current-locale-to-cache-keys)   \n[#36 Setting up tests to avoid retain cycles with weak references](https://github.com/JohnSundell/SwiftTips#36-setting-up-tests-to-avoid-retain-cycles-with-weak-references)   \n[#35 Expressively matching a value against a list of candidates](https://github.com/JohnSundell/SwiftTips#35-expressively-matching-a-value-against-a-list-of-candidates)   \n[#34 Organizing code using extensions](https://github.com/JohnSundell/SwiftTips#34-organizing-code-using-extensions)   \n[#33 Using map to transform an optional into a Result type](https://github.com/JohnSundell/SwiftTips#33-using-map-to-transform-an-optional-into-a-result-type)   \n[#32 Assigning to self in struct initializers](https://github.com/JohnSundell/SwiftTips#32-assigning-to-self-in-struct-initializers)   \n[#31 Recursively calling closures as inline functions](https://github.com/JohnSundell/SwiftTips#31-recursively-calling-closures-as-inline-functions)   \n[#30 Passing self to required Objective-C dependencies](https://github.com/JohnSundell/SwiftTips#30-passing-self-to-required-objective-c-dependencies)   \n[#29 Making weak or lazy properties readonly](https://github.com/JohnSundell/SwiftTips#29-making-weak-or-lazy-properties-readonly)   \n[#28 Defining static URLs using string literals](https://github.com/JohnSundell/SwiftTips#28-defining-static-urls-using-string-literals)   \n[#27 Manipulating points, sizes and frames using math operators](https://github.com/JohnSundell/SwiftTips#27-manipulating-points-sizes-and-frames-using-math-operators)   \n[#26 Using closure types in generic constraints](https://github.com/JohnSundell/SwiftTips#26-using-closure-types-in-generic-constraints)   \n[#25 Using associated enum values to avoid state-specific optionals](https://github.com/JohnSundell/SwiftTips#25-using-associated-enum-values-to-avoid-state-specific-optionals)   \n[#24 Using enums for async result types](https://github.com/JohnSundell/SwiftTips#24-using-enums-for-async-result-types)   \n[#23 Working on async code in a playground](https://github.com/JohnSundell/SwiftTips#23-working-on-async-code-in-a-playground)   \n[#22 Overriding self with a weak reference](https://github.com/JohnSundell/SwiftTips#22-overriding-self-with-a-weak-reference)   \n[#21 Using DispatchWorkItem](https://github.com/JohnSundell/SwiftTips#21-using-dispatchworkitem)   \n[#20 Combining a sequence of functions](https://github.com/JohnSundell/SwiftTips#20-combining-a-sequence-of-functions)   \n[#19 Chaining optionals with map() and flatMap()](https://github.com/JohnSundell/SwiftTips#19-chaining-optionals-with-map-and-flatmap)   \n[#18 Using self-executing closures for lazy properties](https://github.com/JohnSundell/SwiftTips#18-using-self-executing-closures-for-lazy-properties)   \n[#17 Speeding up Swift package tests](https://github.com/JohnSundell/SwiftTips#17-speeding-up-swift-package-tests)   \n[#16 Avoiding mocking UserDefaults](https://github.com/JohnSundell/SwiftTips#16-avoiding-mocking-userdefaults)   \n[#15 Using variadic parameters](https://github.com/JohnSundell/SwiftTips#15-using-variadic-parameters)   \n[#14 Referring to enum cases with associated values as closures](https://github.com/JohnSundell/SwiftTips#14-referring-to-enum-cases-with-associated-values-as-closures)   \n[#13 Using the === operator to compare objects by instance](https://github.com/JohnSundell/SwiftTips#13-using-the--operator-to-compare-objects-by-instance)   \n[#12 Calling initializers with dot syntax and passing them as closures](https://github.com/JohnSundell/SwiftTips#12-calling-initializers-with-dot-syntax-and-passing-them-as-closures)   \n[#11 Structuring UI tests as extensions on XCUIApplication](https://github.com/JohnSundell/SwiftTips#11-structuring-ui-tests-as-extensions-on-xcuiapplication)   \n[#10 Avoiding default cases in switch statements](https://github.com/JohnSundell/SwiftTips#10-avoiding-default-cases-in-switch-statements)   \n[#9 Using the guard statement in many different scopes](https://github.com/JohnSundell/SwiftTips#9-using-the-guard-statement-in-many-different-scopes)   \n[#8 Passing functions \u0026 operators as closures](https://github.com/JohnSundell/SwiftTips#8-passing-functions--operators-as-closures)   \n[#7 Using #function for UserDefaults key consistency](https://github.com/JohnSundell/SwiftTips#7-using-function-for-userdefaults-key-consistency)   \n[#6 Using a name already taken by the standard library](https://github.com/JohnSundell/SwiftTips#6-using-a-name-already-taken-by-the-standard-library)   \n[#5 Using Wrap to implement Equatable](https://github.com/JohnSundell/SwiftTips#5-using-wrap-to-implement-equatable)   \n[#4 Using typealiases to reduce the length of method signatures](https://github.com/JohnSundell/SwiftTips#4-using-typealiases-to-reduce-the-length-of-method-signatures)   \n[#3 Referencing either external or internal parameter name when writing docs](https://github.com/JohnSundell/SwiftTips#3-referencing-either-external-or-internal-parameter-name-when-writing-docs)   \n[#2 Using auto closures](https://github.com/JohnSundell/SwiftTips#2-using-auto-closures)   \n[#1 Namespacing with nested types](https://github.com/JohnSundell/SwiftTips#1-namespacing-with-nested-types)\n\n## [#102 Making async tests faster and more stable](https://twitter.com/johnsundell/status/1062444638479491073)\n\n🚀 Here are some quick tips to make async tests faster \u0026 more stable:\n\n- 😴 Avoid sleep() - use expectations instead\n- ⏱ Use generous timeouts to avoid flakiness on CI\n- 🧐 Put all assertions at the end of each test, not inside closures\n\n```swift\n// BEFORE:\n\nclass MentionDetectorTests: XCTestCase {\n    func testDetectingMention() {\n        let detector = MentionDetector()\n        let string = \"This test was written by @johnsundell.\"\n\n        detector.detectMentions(in: string) { mentions in\n            XCTAssertEqual(mentions, [\"johnsundell\"])\n        }\n        \n        sleep(2)\n    }\n}\n\n// AFTER:\n\nclass MentionDetectorTests: XCTestCase {\n    func testDetectingMention() {\n        let detector = MentionDetector()\n        let string = \"This test was written by @johnsundell.\"\n\n        var mentions: [String]?\n        let expectation = self.expectation(description: #function)\n\n        detector.detectMentions(in: string) {\n            mentions = $0\n            expectation.fulfill()\n        }\n\n        waitForExpectations(timeout: 10)\n        XCTAssertEqual(mentions, [\"johnsundell\"])\n    }\n}\n```\n\n*For more on async testing, check out [\"Unit testing asynchronous Swift code\"](https://www.swiftbysundell.com/posts/unit-testing-asynchronous-swift-code).*\n\n## [#101 Adding support for Apple Pencil double-taps](https://twitter.com/johnsundell/status/1060295659549528064)\n\n✍️ Adding support for the new Apple Pencil double-tap feature is super easy! All you have to do is to create a `UIPencilInteraction`, add it to a view, and implement one delegate method. Hopefully all pencil-compatible apps will soon adopt this.\n\n```swift\nlet interaction = UIPencilInteraction()\ninteraction.delegate = self\nview.addInteraction(interaction)\n\nextension ViewController: UIPencilInteractionDelegate {\n    func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {\n        // Handle pencil double-tap\n    }\n}\n```\n\n*For more on using this and other iPad Pro features, check out [\"Building iPad Pro features in Swift\"](https://www.swiftbysundell.com/posts/building-ipad-pro-features-in-swift).*\n\n## [#100 Combining values with functions](https://twitter.com/johnsundell/status/1055562781070684162)\n\n😎 Here's a cool function that combines a value with a function to return a closure that captures that value, so that it can be called without any arguments. Super useful when working with closure-based APIs and we want to use some of our properties without having to capture `self`.\n\n```swift\nfunc combine\u003cA, B\u003e(_ value: A, with closure: @escaping (A) -\u003e B) -\u003e () -\u003e B {\n    return { closure(value) }\n}\n\n// BEFORE:\n\nclass ProductViewController: UIViewController {\n    override func viewDidLoad() {\n        super.viewDidLoad()\n\n        buyButton.handler = { [weak self] in\n            guard let self = self else {\n                return\n            }\n            \n            self.productManager.startCheckout(for: self.product)\n        }\n    }\n}\n\n// AFTER:\n\nclass ProductViewController: UIViewController {\n    override func viewDidLoad() {\n        super.viewDidLoad()\n\n        buyButton.handler = combine(product, with: productManager.startCheckout)\n    }\n}\n```\n\n## [#99 Dependency injection using functions](https://twitter.com/johnsundell/status/1054810472564879360)\n\n💉 When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection \u0026 testing super simple.\n\n```swift\nfinal class ArticleLoader {\n    typealias Networking = (Endpoint) -\u003e Future\u003cData\u003e\n    \n    private let networking: Networking\n    \n    init(networking: @escaping Networking = URLSession.shared.load) {\n        self.networking = networking\n    }\n    \n    func loadLatest() -\u003e Future\u003c[Article]\u003e {\n        return networking(.latestArticles).decode()\n    }\n}\n```\n\n*For more on this technique, check out [\"Simple Swift dependency injection with functions\"](https://www.swiftbysundell.com/posts/simple-swift-dependency-injection-with-functions).*\n\n## [#98 Using a custom exception handler](https://twitter.com/johnsundell/status/1052282169807306755)\n\n💥 It's cool that you can easily assign a closure as a custom `NSException` handler. This is super useful when building things in Playgrounds - since you can't use breakpoints - so instead of just `signal SIGABRT`, you'll get the full exception description if something goes wrong.\n\n```swift\nNSSetUncaughtExceptionHandler { exception in\n    print(exception)\n}\n```\n\n## [#97 Using type aliases to give semantic meaning to primitives](https://twitter.com/johnsundell/status/1051249295532417024)\n\n❤️ I love that in Swift, we can use the type system to make our code so much more self-documenting - one way of doing so is to use type aliases to give the primitive types that we use a more semantic meaning.\n\n```swift\nextension List.Item {\n    // Using type aliases, we can give semantic meaning to the\n    // primitive types that we use, without having to introduce\n    // wrapper types.\n    typealias Index = Int\n}\n\nextension List {\n    enum Mutation {\n        // Our enum cases now become a lot more self-documenting,\n        // without having to add additional parameter labels to\n        // explain them.\n        case add(Item, Item.Index)\n        case update(Item, Item.Index)\n        case remove(Item.Index)\n    }\n}\n```\n\n*For more on self-documenting code, check out [\"Writing self-documenting Swift code\"](https://www.swiftbysundell.com/posts/writing-self-documenting-swift-code).*\n\n## [#96 Specializing protocols using constraints](https://twitter.com/johnsundell/status/1049428419040215040)\n\n🤯 A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!\n\nThis is awesome, since it lets us easily define specialized protocols based on more generic ones.\n\n```swift\nprotocol Component {\n    associatedtype Container\n    func add(to container: Container)\n}\n\n// Protocols that inherit from other protocols can include\n// constraints to further specialize them.\nprotocol ViewComponent: Component where Container == UIView {\n    associatedtype View: UIView\n    var view: View { get }\n}\n\nextension ViewComponent {\n    func add(to container: UIView) {\n        container.addSubview(view)\n    }\n}\n```\n\n*For more on specializing protocols, check out [\"Specializing protocols in Swift\"](https://www.swiftbysundell.com/posts/specializing-protocols-in-swift).*\n\n## [#95 Unwrapping an optional or throwing an error](https://twitter.com/johnsundell/status/1047232852113412098)\n\n📦 Here's a super handy extension on Swift's `Optional` type, which gives us a really nice API for easily unwrapping an optional, or throwing an error in case the value turned out to be `nil`:\n\n```swift\nextension Optional {\n    func orThrow(_ errorExpression: @autoclosure () -\u003e Error) throws -\u003e Wrapped {\n        switch self {\n        case .some(let value):\n            return value\n        case .none:\n            throw errorExpression()\n        }\n    }\n}\n\nlet file = try loadFile(at: path).orThrow(MissingFileError())\n```\n\n*For more ways that optionals can be extended, check out [\"Extending optionals in Swift\"](https://www.swiftbysundell.com/posts/extending-optionals-in-swift).*\n\n## [#94 Testing code that uses static APIs](https://twitter.com/johnsundell/status/1044900209841590272)\n\n👩‍🔬 Testing code that uses static APIs can be really tricky, but there's a way that it can often be done - using Swift's first class function capabilities!\n\nInstead of accessing that static API directly, we can inject the function we want to use, which enables us to mock it!\n\n```swift\n// BEFORE\n\nclass FriendsLoader {\n    func loadFriends(then handler: @escaping (Result\u003c[Friend]\u003e) -\u003e Void) {\n        Networking.loadData(from: .friends) { result in\n            ...\n        }\n    }\n}\n\n// AFTER\n\nclass FriendsLoader {\n    typealias Handler\u003cT\u003e = (Result\u003cT\u003e) -\u003e Void\n    typealias DataLoadingFunction = (Endpoint, @escaping Handler\u003cData\u003e) -\u003e Void\n\n    func loadFriends(using dataLoading: DataLoadingFunction = Networking.loadData,\n                     then handler: @escaping Handler\u003c[Friend]\u003e) {\n        dataLoading(.friends) { result in\n            ...\n        }\n    }\n}\n\n// MOCKING IN TESTS\n\nlet dataLoading: FriendsLoader.DataLoadingFunction = { _, handler in\n    handler(.success(mockData))\n}\n\nfriendsLoader.loadFriends(using: dataLoading) { result in\n    ...\n}\n```\n\n## [#93 Matching multiple enum cases with associated values](https://twitter.com/johnsundell/status/1039882780174413824)\n\n🐾 Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.\n\n```swift\nenum DownloadState {\n    case inProgress(progress: Double)\n    case paused(progress: Double)\n    case cancelled\n    case finished(Data)\n}\n\nfunc downloadStateDidChange(to state: DownloadState) {\n    switch state {\n    case .inProgress(let progress), .paused(let progress):\n        updateProgressView(with: progress)\n    case .cancelled:\n        showCancelledMessage()\n    case .finished(let data):\n        process(data)\n    }\n}\n```\n\n## [#92 Multiline string literals](https://twitter.com/johnsundell/status/1034037108921516032)\n\n🅰 One really nice benefit of Swift multiline string literals - even for single lines of text - is that they don't require quotes to be escaped. Perfect when working with things like HTML, or creating a custom description for an object.\n\n```swift\nlet html = highlighter.highlight(\"Array\u003cString\u003e\")\n\nXCTAssertEqual(html, \"\"\"\n\u003cspan class=\"type\"\u003eArray\u003c/span\u003e\u0026lt;\u003cspan class=\"type\"\u003eString\u003c/span\u003e\u0026gt;\n\"\"\")\n```\n\n## [#91 Reducing sequences](https://twitter.com/johnsundell/status/1030458678875439109)\n\n💎 While it's very common in functional programming, the `reduce` function might be a bit of a hidden gem in Swift. It provides a super useful way to transform a sequence into a single value.\n\n```swift\nextension Sequence where Element: Equatable {\n    func numberOfOccurrences(of target: Element) -\u003e Int {\n        return reduce(0) { result, element in\n            guard element == target else {\n                return result\n            }\n\n            return result + 1\n        }\n    }\n}\n```\n\nYou can read more about transforming collections in *[\"Transforming collections in Swift\"](https://www.swiftbysundell.com/posts/transforming-collections-in-swift)*.\n\n## [#90 Avoiding manual Codable implementations](https://twitter.com/johnsundell/status/1030064777941471232)\n\n📦 When I use Codable in Swift, I want to avoid manual implementations as much as possible, even when there's a mismatch between my code structure and the JSON I'm decoding.\n\nOne way that can often be achieved is to use private data containers combined with computed properties.\n\n```swift\nstruct User: Codable {\n    let name: String\n    let age: Int\n\n    var homeTown: String { return originPlace.name }\n\n    private let originPlace: Place\n}\n\nprivate extension User {\n    struct Place: Codable {\n        let name: String\n    }\n}\n\nextension User {\n    struct Container: Codable {\n        let user: User\n    }\n}\n```\n\n## [#89 Using feature flags instead of feature branches](https://twitter.com/johnsundell/status/1019574434338877440)\n\n🚢 Instead of using feature branches, I merge almost all of my code directly into master - and then I use feature flags to conditionally enable features when they're ready. That way I can avoid merge conflicts and keep shipping!\n\n```swift\nextension ListViewController {\n    func addSearchIfNeeded() {\n        // Rather than having to keep maintaining a separate\n        // feature branch for a new feature, we can use a flag\n        // to conditionally turn it on.\n        guard FeatureFlags.searchEnabled else {\n            return\n        }\n\n        let resultsVC = SearchResultsViewController()\n        let searchVC = UISearchController(\n            searchResultsController: resultsVC\n        )\n\n        searchVC.searchResultsUpdater = resultsVC\n        navigationItem.searchController = searchVC\n    }\n}\n```\n\n*You can read more about feature flags in [\"Feature flags in Swift\"](https://www.swiftbysundell.com/posts/feature-flags-in-swift).*\n\n## [#88 Lightweight data hierarchies using tuples](https://twitter.com/johnsundell/status/1018945940252774400)\n\n💾 Here I'm using tuples to create a lightweight hierarchy for my data, giving me a nice structure without having to introduce any additional types.\n\n```swift\nstruct CodeSegment {\n    var tokens: (\n        previous: String?,\n        current: String\n    )\n\n    var delimiters: (\n        previous: Character?\n        next: Character?\n    )\n}\n\nhandle(segment.tokens.current)\n```\n\n*You can read more about tuples in [\"Using tuples as lightweight types in Swift\"](https://www.swiftbysundell.com/posts/using-tuples-as-lightweight-types-in-swift)*\n\n## [#87 The rule of threes](https://twitter.com/johnsundell/status/1012314573112791042)\n\n3️⃣ Whenever I have 3 properties or local variables that share the same prefix, I usually try to extract them into their own method or type. That way I can avoid massive types \u0026 methods, and also increase readability, without falling into a \"premature optimization\" trap.\n\n**Before**\n\n```swift\npublic func generate() throws {\n    let contentFolder = try folder.subfolder(named: \"content\")\n\n    let articleFolder = try contentFolder.subfolder(named: \"posts\")\n    let articleProcessor = ContentProcessor(folder: articleFolder)\n    let articles = try articleProcessor.process()\n\n    ...\n}\n```\n\n**After**\n\n```swift\npublic func generate() throws {\n    let contentFolder = try folder.subfolder(named: \"content\")\n    let articles = try processArticles(in: contentFolder)\n    ...\n}\n\nprivate func processArticles(in folder: Folder) throws -\u003e [ContentItem] {\n    let folder = try folder.subfolder(named: \"posts\")\n    let processor = ContentProcessor(folder: folder)\n    return try processor.process()\n}\n```\n\n## [#86 Useful Codable extensions](https://twitter.com/johnsundell/status/1004290487799468032)\n\n👨‍🔧 Here's two extensions that I always add to the `Encodable` \u0026 `Decodable` protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.\n\n```swift\nextension Encodable {\n    func encoded() throws -\u003e Data {\n        return try JSONEncoder().encode(self)\n    }\n}\n\nextension Data {\n    func decoded\u003cT: Decodable\u003e() throws -\u003e T {\n        return try JSONDecoder().decode(T.self, from: self)\n    }\n}\n\nlet data = try user.encoded()\n\n// By using a generic type in the decoded() method, the\n// compiler can often infer the type we want to decode\n// from the current context.\ntry userDidLogin(data.decoded())\n\n// And if not, we can always supply the type, still making\n// the call site read very nicely.\nlet otherUser = try data.decoded() as User\n```\n\n## [#85 Using shared UserDefaults suites](https://twitter.com/johnsundell/status/1001740057634582528)\n\n📦 `UserDefaults` is a lot more powerful than what it first might seem like. Not only can it store more complex values (like dates \u0026 dictionaries) and parse command line arguments - it also enables easy sharing of settings \u0026 lightweight data between apps in the same App Group.\n\n```swift\nlet sharedDefaults = UserDefaults(suiteName: \"my-app-group\")!\nlet useDarkMode = sharedDefaults.bool(forKey: \"dark-mode\")\n\n// This value is put into the shared suite.\nsharedDefaults.set(true, forKey: \"dark-mode\")\n\n// If you want to treat the shared settings as read-only (and add\n// local overrides on top of them), you can simply add the shared\n// suite to the standard UserDefaults.\nlet combinedDefaults = UserDefaults.standard\ncombinedDefaults.addSuite(named: \"my-app-group\")\n\n// This value is a local override, not added to the shared suite.\ncombinedDefaults.set(true, forKey: \"app-specific-override\")\n```\n\n## [#84 Custom UIView backing layers](https://twitter.com/johnsundell/status/1000099872580816897)\n\n🎨 By overriding `layerClass` you can tell UIKit what `CALayer` class to use for a `UIView`'s backing layer. That way you can reduce the amount of layers, and don't have to do any manual layout.\n\n```swift\nfinal class GradientView: UIView {\n    override class var layerClass: AnyClass { return CAGradientLayer.self }\n\n    var colors: (start: UIColor, end: UIColor)? {\n        didSet { updateLayer() }\n    }\n\n    private func updateLayer() {\n        let layer = self.layer as! CAGradientLayer\n        layer.colors = colors.map { [$0.start.cgColor, $0.end.cgColor] }\n    }\n}\n```\n\n## [#83 Auto-Equatable enums with associated values](https://twitter.com/johnsundell/status/999742519205392389)\n\n✅ That the compiler now automatically synthesizes Equatable conformances is such a huge upgrade for Swift! And the cool thing is that it works for all kinds of types - even for enums with associated values! Especially useful when using enums for verification in unit tests.\n\n```swift\nstruct Article: Equatable {\n    let title: String\n    let text: String\n}\n\nstruct User: Equatable {\n    let name: String\n    let age: Int\n}\n\nextension Navigator {\n    enum Destination: Equatable {\n        case profile(User)\n        case article(Article)\n    }\n}\n\nfunc testNavigatingToArticle() {\n    let article = Article(title: \"Title\", text: \"Text\")\n    controller.select(article)\n    XCTAssertEqual(navigator.destinations, [.article(article)])\n}\n```\n\n## [#82 Defaults for associated types](https://twitter.com/johnsundell/status/997183435759382529)\n\n🤝 Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).\n\n```swift\nprotocol Identifiable {\n    associatedtype RawIdentifier: Codable = String\n\n    var id: Identifier\u003cSelf\u003e { get }\n}\n\nstruct User: Identifiable {\n    let id: Identifier\u003cUser\u003e\n    let name: String\n}\n\nstruct Group: Identifiable {\n    typealias RawIdentifier = Int\n\n    let id: Identifier\u003cGroup\u003e\n    let name: String\n}\n```\n\n## [#81 Creating a dedicated identifier type](https://twitter.com/johnsundell/status/993570941887242240)\n\n🆔 If you want to avoid using plain strings as identifiers (which can increase both type safety \u0026 readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!\n\n*More on this topic in [\"Type-safe identifiers in Swift\"](https://www.swiftbysundell.com/posts/type-safe-identifiers-in-swift).*\n\n```swift\nstruct Identifier: Hashable {\n    let string: String\n}\n\nextension Identifier: ExpressibleByStringLiteral {\n    init(stringLiteral value: String) {\n        string = value\n    }\n}\n\nextension Identifier: CustomStringConvertible {\n    var description: String {\n        return string\n    }\n}\n\nextension Identifier: Codable {\n    init(from decoder: Decoder) throws {\n        let container = try decoder.singleValueContainer()\n        string = try container.decode(String.self)\n    }\n\n    func encode(to encoder: Encoder) throws {\n        var container = encoder.singleValueContainer()\n        try container.encode(string)\n    }\n}\n\nstruct Article: Codable {\n    let id: Identifier\n    let title: String\n}\n\nlet article = Article(id: \"my-article\", title: \"Hello world!\")\n```\n\n## [#80 Assigning optional tuple members to variables](https://twitter.com/johnsundell/status/991047171087650816)\n\n🙌 A really cool thing about using tuples to model the internal state of a Swift type, is that you can unwrap an optional tuple's members directly into local variables.\n\nVery useful in order to group multiple optional values together for easy unwrapping \u0026 handling.\n\n```swift\nclass ImageTransformer {\n    private var queue = [(image: UIImage, transform: Transform)]()\n\n    private func processNext() {\n        // When unwrapping an optional tuple, you can assign the members\n        // directly to local variables.\n        guard let (image, transform) = queue.first else {\n            return\n        }\n\n        let context = Context()\n        context.draw(image)\n        context.apply(transform)\n        ...\n    }\n}\n```\n\n## [#79 Struct convenience initializers](https://twitter.com/johnsundell/status/989470243008458752)\n\n❤️ I love to structure my code using extensions in Swift. One big benefit of doing so when it comes to struct initializers, is that defining a convenience initializer doesn't remove the default one the compiler generates - best of both worlds!\n\n```swift\nstruct Article {\n    let date: Date\n    var title: String\n    var text: String\n    var comments: [Comment]\n}\n\nextension Article {\n    init(title: String, text: String) {\n        self.init(date: Date(), title: title, text: text, comments: [])\n    }\n}\n\nlet articleA = Article(title: \"Best Cupcake Recipe\", text: \"...\")\n\nlet articleB = Article(\n    date: Date(),\n    title: \"Best Cupcake Recipe\",\n    text: \"...\",\n    comments: [\n        Comment(user: currentUser, text: \"Yep, can confirm!\")\n    ]\n)\n```\n\n## [#78 Usages of throwing functions](https://twitter.com/johnsundell/status/988713137854668800)\n\n🏈 A big benefit of using throwing functions for synchronous Swift APIs is that the caller can decide whether they want to treat the return value as optional (`try?`) or required (`try`).\n\n```swift\nfunc loadFile(named name: String) throws -\u003e File {\n    guard let url = urlForFile(named: name) else {\n        throw File.Error.missing\n    }\n\n    do {\n        let data = try Data(contentsOf: url)\n        return File(url: url, data: data)\n    } catch {\n        throw File.Error.invalidData(error)\n    }\n}\n\nlet requiredFile = try loadFile(named: \"AppConfig.json\")\n\nlet optionalFile = try? loadFile(named: \"UserSettings.json\")\n```\n\n## [#77 Nested generic types](https://twitter.com/johnsundell/status/983798689994035200)\n\n🐝 Types that are nested in generics automatically inherit their parent's generic types - which is super useful when defining accessory types (for things like states or outcomes).\n\n```swift\nstruct Task\u003cInput, Output\u003e {\n    typealias Closure = (Input) throws -\u003e Output\n\n    let closure: Closure\n}\n\nextension Task {\n    enum Result {\n        case success(Output)\n        case failure(Error)\n    }\n}\n```\n\n## [#76 Equatable \u0026 Hashable structures](https://twitter.com/johnsundell/status/981449931134259202)\n\n🤖 Now that the Swift compiler automatically synthesizes Equatable \u0026 Hashable conformances for value types, it's easier than ever to setup model structures with nested types that are all `Equatable`/`Hashable`!\n\n```swift\ntypealias Value = Hashable \u0026 Codable\n\nstruct User: Value {\n    var name: String\n    var age: Int\n    var lastLoginDate: Date?\n    var settings: Settings\n}\n\nextension User {\n    struct Settings: Value {\n        var itemsPerPage: Int\n        var theme: Theme\n    }\n}\n\nextension User.Settings {\n    enum Theme: String, Value {\n        case light\n        case dark\n    }\n}\n```\n\n*[You can read more about using nested types in Swift here](https://www.swiftbysundell.com/posts/namespacing-swift-code-with-nested-types).*\n\n## [#75 Conditional conformances](https://twitter.com/johnsundell/status/979682447544737792)\n\n🎉 Swift 4.1 is here! One of the key features it brings is conditional conformances, which lets you have a type only conform to a protocol under certain constraints.\n\n```swift\nprotocol UnboxTransformable {\n    associatedtype RawValue\n\n    static func transform(_ value: RawValue) throws -\u003e Self?\n}\n\nextension Array: UnboxTransformable where Element: UnboxTransformable {\n    typealias RawValue = [Element.RawValue]\n\n    static func transform(_ value: RawValue) throws -\u003e [Element]? {\n        return try value.compactMap(Element.transform)\n    }\n}\n```\n\n*I also have [an article with lots of more info on conditional conformances here](https://www.swiftbysundell.com/posts/conditional-conformances-in-swift). Paul Hudson also has a great overview of [all Swift 4.1 features here](https://www.hackingwithswift.com/articles/50/whats-new-in-swift-4-1).*\n\n## [#74 Generic type aliases](https://twitter.com/johnsundell/status/979059265238388739)\n\n🕵️‍♀️ A cool thing about Swift type aliases is that they can be generic! Combine that with tuples and you can easily define simple generic types.\n\n```swift\ntypealias Pair\u003cT\u003e = (T, T)\n\nextension Game {\n    func calculateScore(for players: Pair\u003cPlayer\u003e) -\u003e Int {\n        ...\n    }\n}\n```\n\n*You can read more about using tuples as lightweight types [here](https://www.swiftbysundell.com/posts/using-tuples-as-lightweight-types-in-swift).*\n\n## [#73 Parsing command line arguments using UserDefaults](https://twitter.com/johnsundell/status/973273054699773953)\n\n☑️ A really cool \"hidden\" feature of UserDefaults is that it contains any arguments that were passed to the app at launch!\n\nSuper useful both in Swift command line tools \u0026 scripts, but also to temporarily override a value when debugging iOS apps.\n\n```swift\nlet defaults = UserDefaults.standard\nlet query = defaults.string(forKey: \"query\")\nlet resultCount = defaults.integer(forKey: \"results\")\n```\n\n## [#72 Using the \u0026 operator](https://twitter.com/johnsundell/status/972134523612925952)\n\n👏 Swift's `\u0026` operator is awesome! Not only can you use it to compose protocols, you can compose other types too! Very useful if you want to hide concrete types \u0026 implementation details.\n\n```swift\nprotocol LoadableFromURL {\n    func load(from url: URL)\n}\n\nclass ContentViewController: UIViewController, LoadableFromURL {\n    func load(from url: URL) {\n        ...\n    }\n}\n\nclass ViewControllerFactory {\n    func makeContentViewController() -\u003e UIViewController \u0026 LoadableFromURL {\n        return ContentViewController()\n    }\n}\n```\n\n## [#71 Capturing multiple values in mocks](https://twitter.com/johnsundell/status/971675443307917314)\n\n🤗 When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.\n\nPerfect for protecting against \"over-calling\" something.\n\n```swift\nclass UserManagerTests: XCTestCase {\n    func testObserversCalledWhenUserFirstLogsIn() {\n        let manager = UserManager()\n\n        let observer = ObserverMock()\n        manager.addObserver(observer)\n\n        // First login, observers should be notified\n        let user = User(id: 123, name: \"John\")\n        manager.userDidLogin(user)\n        XCTAssertEqual(observer.users, [user])\n\n        // If the same user logs in again, observers shouldn't be notified\n        manager.userDidLogin(user)\n        XCTAssertEqual(observer.users, [user])\n    }\n}\n\nprivate extension UserManagerTests {\n    class ObserverMock: UserManagerObserver {\n        private(set) var users = [User]()\n\n        func userDidChange(to user: User) {\n            users.append(user)\n        }\n    }\n}\n```\n\n## [#70 Reducing the need for mocks](https://twitter.com/johnsundell/status/966652150247055360)\n\n👋 When writing tests, you don't always need to create mocks - you can create stubs using real instances of things like errors, URLs \u0026 UserDefaults.\n\nHere's how to do that for some common tasks/object types in Swift:\n\n```swift\n// Create errors using NSError (#function can be used to reference the name of the test)\nlet error = NSError(domain: #function, code: 1, userInfo: nil)\n\n// Create non-optional URLs using file paths\nlet url = URL(fileURLWithPath: \"Some/URL\")\n\n// Reference the test bundle using Bundle(for:)\nlet bundle = Bundle(for: type(of: self))\n\n// Create an explicit UserDefaults object (instead of having to use a mock)\nlet userDefaults = UserDefaults(suiteName: #function)\n\n// Create queues to control/await concurrent operations\nlet queue = DispatchQueue(label: #function)\n```\n\n*For when you actually do need mocking, check out [\"Mocking in Swift\"](https://www.swiftbysundell.com/posts/mocking-in-swift).*\n\n## [#69 Using \"then\" as an external parameter label for closures](https://twitter.com/johnsundell/status/965880323614695424)\n\n⏱ I've started using \"then\" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do ❤️ conversational API design) regardless of whether trailing closure syntax is used or not.\n\n```swift\nprotocol DataLoader {\n    // Adding type aliases to protocols can be a great way to\n    // reduce verbosity for parameter types.\n    typealias Handler = (Result\u003cData\u003e) -\u003e Void\n    associatedtype Endpoint\n\n    func loadData(from endpoint: Endpoint, then handler: @escaping Handler)\n}\n\nloader.loadData(from: .messages) { result in\n    ...\n}\n\nloader.loadData(from: .messages, then: { result in\n    ...\n})\n```\n\n## [#68 Combining lazily evaluated sequences with the builder pattern](https://twitter.com/johnsundell/status/964515011765899266)\n\n😴 Combining lazily evaluated sequences with builder pattern-like properties can lead to some pretty sweet APIs for configurable sequences in Swift.\n\nAlso useful for queries \u0026 other things you \"build up\" and then execute.\n\n```swift\n// Extension adding builder pattern-like properties that return\n// a new sequence value with the given configuration applied\nextension FileSequence {\n    var recursive: FileSequence {\n        var sequence = self\n        sequence.isRecursive = true\n        return sequence\n    }\n\n    var includingHidden: FileSequence {\n        var sequence = self\n        sequence.includeHidden = true\n        return sequence\n    }\n}\n\n// BEFORE\n\nlet files = folder.makeFileSequence(recursive: true, includeHidden: true)\n\n// AFTER\n\nlet files = folder.files.recursive.includingHidden\n```\n\nWant an intro to lazy sequences? Check out *[\"Swift sequences: The art of being lazy\"](https://www.swiftbysundell.com/posts/swift-sequences-the-art-of-being-lazy)*.\n\n## [#67 Faster \u0026 more stable UI tests](https://twitter.com/johnsundell/status/960578271439138816)\n\nMy top 3 tips for faster \u0026 more stable UI tests:\n\n📱 Reset the app's state at the beginning of every test.\n\n🆔 Use accessibility identifiers instead of UI strings.\n\n⏱ Use expectations instead of waiting time.\n\n```swift\nfunc testOpeningArticle() {\n    // Launch the app with an argument that tells it to reset its state\n    let app = XCUIApplication()\n    app.launchArguments.append(\"--uitesting\")\n    app.launch()\n    \n    // Check that the app is displaying an activity indicator\n    let activityIndicator = app.activityIndicator.element\n    XCTAssertTrue(activityIndicator.exists)\n    \n    // Wait for the loading indicator to disappear = content is ready\n    expectation(for: NSPredicate(format: \"exists == 0\"),\n                evaluatedWith: activityIndicator)\n                \n    // Use a generous timeout in case the network is slow\n    waitForExpectations(timeout: 10)\n    \n    // Tap the cell for the first article\n    app.tables.cells[\"Article.0\"].tap()\n    \n    // Assert that a label with the accessibility identifier \"Article.Title\" exists\n    let label = app.staticTexts[\"Article.Title\"]\n    XCTAssertTrue(label.exists)\n}\n```\n\n## [#66 Accessing the clipboard from a Swift script](https://twitter.com/johnsundell/status/959875189961056256)\n\n📋 It's super easy to access the contents of the clipboard from a Swift script. A big benefit of Swift scripting is being able to use Cocoa's powerful APIs for Mac apps.\n\n```swift\nimport Cocoa\n\nlet clipboard = NSPasteboard.general.string(forType: .string)\n```\n\n## [#65 Using tuples for view state](https://twitter.com/johnsundell/status/958374853555511296)\n\n🎯 Using Swift tuples for view state can be a super nice way to group multiple properties together and render them reactively using the layout system.\n\nBy using a tuple we don't have to either introduce a new type or make our view model-aware.\n\n```swift\nclass TextView: UIView {\n    var state: (title: String?, text: String?) {\n        // By telling UIKit that our view needs layout and binding our\n        // state in layoutSubviews, we can react to state changes without\n        // doing unnecessary layout work.\n        didSet { setNeedsLayout() }\n    }\n\n    private let titleLabel = UILabel()\n    private let textLabel = UILabel()\n\n    override func layoutSubviews() {\n        super.layoutSubviews()\n\n        titleLabel.text = state.title\n        textLabel.text = state.text\n\n        ...\n    }\n}\n```\n\n## [#64 Throwing tests and LocalizedError](https://twitter.com/johnsundell/status/956630510628999171)\n\n⚾️ Swift tests can throw, which is super useful in order to avoid complicated logic or force unwrapping. By making errors conform to `LocalizedError`, you can also get a nice error message in Xcode if there's a failure.\n\n```swift\nclass ImageCacheTests: XCTestCase {\n    func testCachingAndLoadingImage() throws {\n        let bundle = Bundle(for: type(of: self))\n        let cache = ImageCache(bundle: bundle)\n        \n        // Bonus tip: You can easily load images from your test\n        // bundle using this UIImage initializer\n        let image = try require(UIImage(named: \"sample\", in: bundle, compatibleWith: nil))\n        try cache.cache(image, forKey: \"key\")\n        \n        let cachedImage = try cache.image(forKey: \"key\")\n        XCTAssertEqual(image, cachedImage)\n    }\n}\n\nenum ImageCacheError {\n    case emptyKey\n    case dataConversionFailed\n}\n\n// When using throwing tests, making your errors conform to\n// LocalizedError will render a much nicer error message in\n// Xcode (per default only the error code is shown).\nextension ImageCacheError: LocalizedError {\n    var errorDescription: String? {\n        switch self {\n        case .emptyKey:\n            return \"An empty key was given\"\n        case .dataConversionFailed:\n            return \"Failed to convert the given image to Data\"\n        }\n    }\n}\n```\n\nFor more information, and the implementation of the `require` method used above, check out *[\"Avoiding force unwrapping in Swift unit tests\"](https://www.swiftbysundell.com/posts/avoiding-force-unwrapping-in-swift-unit-tests)*.\n\n## [#63 The difference between static and class properties](https://twitter.com/johnsundell/status/956277711294656512)\n\n✍️ Unlike `static` properties, `class` properties can be overridden by subclasses (however, they can't be stored, only computed).\n\n```swift\nclass TableViewCell: UITableViewCell {\n    class var preferredHeight: CGFloat { return 60 }\n}\n\nclass TallTableViewCell: TableViewCell {\n    override class var preferredHeight: CGFloat { return 100 }\n}\n```\n\n## [#62 Creating extensions with static factory methods](https://twitter.com/johnsundell/status/955832453238751232)\n\n👨‍🎨 Creating extensions with static factory methods can be a great alternative to subclassing in Swift, especially for things like setting up UIViews, CALayers or other kinds of styling.\n\nIt also lets you remove a lot of styling \u0026 setup from your view controllers.\n\n```swift\nextension UILabel {\n    static func makeForTitle() -\u003e UILabel {\n        let label = UILabel()\n        label.font = .boldSystemFont(ofSize: 24)\n        label.textColor = .darkGray\n        label.adjustsFontSizeToFitWidth = true\n        label.minimumScaleFactor = 0.75\n        return label\n    }\n\n    static func makeForText() -\u003e UILabel {\n        let label = UILabel()\n        label.font = .systemFont(ofSize: 16)\n        label.textColor = .black\n        label.numberOfLines = 0\n        return label\n    }\n}\n\nclass ArticleViewController: UIViewController {\n    lazy var titleLabel = UILabel.makeForTitle()\n    lazy var textLabel = UILabel.makeForText()\n}\n```\n\n## [#61 Child view controller auto-resizing](https://twitter.com/johnsundell/status/953999892309045249)\n\n🧒 An awesome thing about child view controllers is that they're automatically resized to match their parent, making them a super nice solution for things like loading \u0026 error views.\n\n```swift\nclass ListViewController: UIViewController {\n    func loadItems() {\n        let loadingViewController = LoadingViewController()\n        add(loadingViewController)\n\n        dataLoader.loadItems { [weak self] result in\n            loadingViewController.remove()\n            self?.handle(result)\n        }\n    }\n}\n```\n\nFor more about child view controller (including the `add` and `remove` methods used above), check out *[\"Using child view controllers as plugins in Swift\"](https://www.swiftbysundell.com/posts/using-child-view-controllers-as-plugins-in-swift)*.\n\n## [#60 Using zip](https://twitter.com/johnsundell/status/953302410209976320)\n\n🤐 Using the zip function in Swift you can easily combine two sequences. Super useful when using two sequences to do some work, since zip takes care of all the bounds-checking.\n\n```swift\nfunc render(titles: [String]) {\n    for (label, text) in zip(titleLabels, titles) {\n        print(text)\n        label.text = text\n    }\n}\n```\n\n## [#59 Defining custom option sets](https://twitter.com/johnsundell/status/951830680522117120)\n\n🎛 The awesome thing about option sets in Swift is that they can automatically either be passed as a single member or as a set. Even cooler is that you can easily define your own option sets as well, perfect for options and other non-exclusive values.\n\n```swift\n// Option sets are awesome, because you can easily pass them\n// both using dot syntax and array literal syntax, like when\n// using the UIView animation API:\nUIView.animate(withDuration: 0.3,\n               delay: 0,\n               options: .allowUserInteraction,\n               animations: animations)\n\nUIView.animate(withDuration: 0.3,\n               delay: 0,\n               options: [.allowUserInteraction, .layoutSubviews],\n               animations: animations)\n\n// The cool thing is that you can easily define your own option\n// sets as well, by defining a struct that has an Int rawValue,\n// that will be used as a bit mask.\nextension Cache {\n    struct Options: OptionSet {\n        static let saveToDisk = Options(rawValue: 1)\n        static let clearOnMemoryWarning = Options(rawValue: 1 \u003c\u003c 1)\n        static let clearDaily = Options(rawValue: 1 \u003c\u003c 2)\n\n        let rawValue: Int\n    }\n}\n\n// We can now use Cache.Options just like UIViewAnimationOptions:\nCache(options: .saveToDisk)\nCache(options: [.saveToDisk, .clearDaily])\n```\n\n## [#58 Using the where clause with associated types](https://twitter.com/johnsundell/status/950810357492256768)\n\n🙌 Using the `where` clause when designing protocol-oriented APIs in Swift can let your implementations (or others' if it's open source) have a lot more freedom, especially when it comes to collections.\n\n*See [\"Using generic type constraints in Swift 4\"](https://www.swiftbysundell.com/posts/using-generic-type-constraints-in-swift-4) for more info.*\n\n```swift\npublic protocol PathFinderMap {\n    associatedtype Node\n    // Using the 'where' clause for associated types, we can\n    // ensure that a type meets certain requirements (in this\n    // case that it's a sequence with Node elements).\n    associatedtype NodeSequence: Sequence where NodeSequence.Element == Node\n\n    // Instead of using a concrete type (like [Node]) here, we\n    // give implementors of this protocol more freedom while\n    // still meeting our requirements. For example, one\n    // implementation might use Set\u003cNode\u003e.\n    func neighbors(of node: Node) -\u003e NodeSequence\n}\n```\n\n## [#57 Using first class functions when iterating over a dictionary](https://twitter.com/johnsundell/status/950455451799445504)\n\n👨‍🍳 Combine first class functions in Swift with the fact that Dictionary elements are (Key, Value) tuples and you can build yourself some pretty awesome functional chains when iterating over a Dictionary.\n\n```swift\nfunc makeActor(at coordinate: Coordinate, for building: Building) -\u003e Actor {\n    let actor = Actor()\n    actor.position = coordinate.point\n    actor.animation = building.animation\n    return actor\n}\n\nfunc render(_ buildings: [Coordinate : Building]) {\n    buildings.map(makeActor).forEach(add)\n}\n```\n\n## [#56 Calling instance methods as static functions](https://twitter.com/johnsundell/status/949317918730440704)\n\n😎 In Swift, you can call any instance method as a static function and it will return a closure representing that method. This is how running tests using SPM on Linux works.\n\n*More about this topic in my blog post [\"First class functions in Swift\"](https://www.swiftbysundell.com/posts/first-class-functions-in-swift).*\n\n```swift\n// This produces a '() -\u003e Void' closure which is a reference to the\n// given view's 'removeFromSuperview' method.\nlet closure = UIView.removeFromSuperview(view)\n\n// We can now call it just like we would any other closure, and it\n// will run 'view.removeFromSuperview()'\nclosure()\n\n// This is how running tests using the Swift Package Manager on Linux\n// works, you return your test functions as closures:\nextension UserManagerTests {\n    static var allTests = [\n        (\"testLoggingIn\", testLoggingIn),\n        (\"testLoggingOut\", testLoggingOut),\n        (\"testUserPermissions\", testUserPermissions)\n    ]\n}\n```\n\n## [#55 Dropping suffixes from method names to support multiple arguments](https://twitter.com/johnsundell/status/948513364015288320)\n\n👏 One really nice benefit of dropping suffixes from method names (and just using verbs, when possible) is that it becomes super easy to support both single and multiple arguments, and it works really well semantically.\n\n```swift\nextension UIView {\n    func add(_ subviews: UIView...) {\n        subviews.forEach(addSubview)\n    }\n}\n\nview.add(button)\nview.add(label)\n\n// By dropping the \"Subview\" suffix from the method name, both\n// single and multiple arguments work really well semantically.\nview.add(button, label)\n```\n\n## [#54 Constraining protocols to classes to ensure mutability](https://twitter.com/johnsundell/status/948267767744122881)\n\n👽 Using the `AnyObject` (or `class`) constraint on protocols is not only useful when defining delegates (or other weak references), but also when you always want instances to be mutable without copying.\n\n```swift\n// By constraining a protocol with 'AnyObject' it can only be adopted\n// by classes, which means all instances will always be mutable, and\n// that it's the original instance (not a copy) that will be mutated.\nprotocol DataContainer: AnyObject {\n    var data: Data? { get set }\n}\n\nclass UserSettingsManager {\n    private var settings: Settings\n    private let dataContainer: DataContainer\n\n    // Since DataContainer is a protocol, we an easily mock it in\n    // tests if we use dependency injection\n    init(settings: Settings, dataContainer: DataContainer) {\n        self.settings = settings\n        self.dataContainer = dataContainer\n    }\n\n    func saveSettings() throws {\n        let data = try settings.serialize()\n\n        // We can now assign properties on an instance of our protocol\n        // because the compiler knows it's always going to be a class\n        dataContainer.data = data\n    }\n}\n```\n\n## [#53 String-based enums in string interpolation](https://twitter.com/johnsundell/status/945686980125437954)\n\n🍣 Even if you define a custom raw value for a string-based enum in Swift, the full case name will be used in string interpolation.\n\nSuper useful when using separate raw values for JSON, while still wanting to use the full case name in other contexts.\n\n```swift\nextension Building {\n    // This enum has custom raw values that are used when decoding\n    // a value, for example from JSON.\n    enum Kind: String {\n        case castle = \"C\"\n        case town = \"T\"\n        case barracks = \"B\"\n        case goldMine = \"G\"\n        case camp = \"CA\"\n        case blacksmith = \"BL\"\n    }\n\n    var animation: Animation {\n        return Animation(\n            // When used in string interpolation, the full case name is still used.\n            // For 'castle' this will be 'buildings/castle'.\n            name: \"buildings/\\(kind)\",\n            frameCount: frameCount,\n            frameDuration: frameDuration\n        )\n    }\n}\n```\n\n## [#52 Expressively comparing a value with a list of candidates](https://twitter.com/johnsundell/status/943510426586959873)\n\n👨‍🔬 Continuing to experiment with expressive ways of comparing a value with a list of candidates in Swift. Adding an extension on Equatable is probably my favorite approach so far.\n\n```swift\nextension Equatable {\n    func isAny(of candidates: Self...) -\u003e Bool {\n        return candidates.contains(self)\n    }\n}\n\nlet isHorizontal = direction.isAny(of: .left, .right)\n```\n\n*See [tip #35](https://github.com/JohnSundell/SwiftTips#35-expressively-matching-a-value-against-a-list-of-candidates) for my previous experiment.*\n\n## [#51 UIView bounds and transforms](https://twitter.com/johnsundell/status/943156901428256770)\n\n📐 A really interesting side-effect of a `UIView`'s `bounds` being its rect within its own coordinate system is that transforms don't affect it at all. That's why it's usually a better fit than `frame` when doing layout calculations of subviews.\n\n```swift\nlet view = UIView()\nview.frame.size = CGSize(width: 100, height: 100)\nview.transform = CGAffineTransform(scaleX: 2, y: 2)\n\nprint(view.frame) // (-50.0, -50.0, 200.0, 200.0)\nprint(view.bounds) // (0.0, 0.0, 100.0, 100.0)\n```\n\n## [#50 UIKit default arguments](https://twitter.com/johnsundell/status/940330427855892480)\n\n👏 It's awesome that many UIKit APIs with completion handlers and other optional parameters import into Swift with default arguments (even though they are written in Objective-C). Getting rid of all those nil arguments is so nice!\n\n```swift\n// BEFORE: All parameters are specified, just like in Objective-C\n\nviewController.present(modalViewController, animated: true, completion: nil)\n\nmodalViewController.dismiss(animated: true, completion: nil)\n\nviewController.transition(from: loadingViewController,\n                          to: contentViewController,\n                          duration: 0.3,\n                          options: [],\n                          animations: animations,\n                          completion: nil)\n\n// AFTER: Since many UIKit APIs with completion handlers and other\n// optional parameters import into Swift with default arguments,\n// we can make our calls shorter\n\nviewController.present(modalViewController, animated: true)\n\nmodalViewController.dismiss(animated: true)\n\nviewController.transition(from: loadingViewController,\n                          to: contentViewController,\n                          duration: 0.3,\n                          animations: animations)\n```\n\n## [#49 Avoiding Massive View Controllers](https://twitter.com/johnsundell/status/938505299723505664)\n\n✂️ Avoiding Massive View Controllers is all about finding the right levels of abstraction and splitting things up.\n\nMy personal rule of thumb is that as soon as I have 3 methods or properties that have the same prefix, I break them out into their own type.\n\n```swift\n// BEFORE\n\nclass LoginViewController: UIViewController {\n    private lazy var signUpLabel = UILabel()\n    private lazy var signUpImageView = UIImageView()\n    private lazy var signUpButton = UIButton()\n}\n\n// AFTER\n\nclass LoginViewController: UIViewController {\n    private lazy var signUpView = SignUpView()\n}\n\nclass SignUpView: UIView {\n    private lazy var label = UILabel()\n    private lazy var imageView = UIImageView()\n    private lazy var button = UIButton()\n}\n```\n\n## [#48 Extending optionals](https://twitter.com/johnsundell/status/938137780760215553)\n\n❤️ I love the fact that optionals are enums in Swift - it makes it so easy to extend them with convenience APIs for certain types. Especially useful when doing things like data validation on optional values.\n\n```swift\nfunc validateTextFields() -\u003e Bool {\n    guard !usernameTextField.text.isNilOrEmpty else {\n        return false\n    }\n\n    ...\n\n    return true\n}\n\n// Since all optionals are actual enum values in Swift, we can easily\n// extend them for certain types, to add our own convenience APIs\n\nextension Optional where Wrapped == String {\n    var isNilOrEmpty: Bool {\n        switch self {\n        case let string?:\n            return string.isEmpty\n        case nil:\n            return true\n        }\n    }\n}\n\n// Since strings are now Collections in Swift 4, you can even\n// add this property to all optional collections:\n\nextension Optional where Wrapped: Collection {\n    var isNilOrEmpty: Bool {\n        switch self {\n        case let collection?:\n            return collection.isEmpty\n        case nil:\n            return true\n        }\n    }\n}\n```\n\n## [#47 Using where with for-loops](https://twitter.com/johnsundell/status/935910564865433601)\n\n🗺 Using the `where` keyword can be a super nice way to quickly apply a filter in a `for`-loop in Swift. You can of course use `map`, `filter` and `forEach`, or `guard`, but for simple loops I think this is very expressive and nice.\n\n```swift\nfunc archiveMarkedPosts() {\n    for post in posts where post.isMarked {\n        archive(post)\n    }\n}\n\nfunc healAllies() {\n    for player in players where player.isAllied(to: currentPlayer) {\n        player.heal()\n    }\n}\n```\n\n## [#46 Variable shadowing](https://twitter.com/johnsundell/status/931549161782169600)\n\n👻 Variable shadowing can be super useful in Swift, especially when you want to create a local copy of a parameter value in order to use it as state within a closure.\n\n```swift\ninit(repeatMode: RepeatMode, closure: @escaping () -\u003e UpdateOutcome) {\n    // Shadow the argument with a local, mutable copy\n    var repeatMode = repeatMode\n    \n    self.closure = {\n        // With shadowing, there's no risk of accidentially\n        // referring to the immutable version\n        switch repeatMode {\n        case .forever:\n            break\n        case .times(let count):\n            guard count \u003e 0 else {\n                return .finished\n            }\n            \n            // We can now capture the mutable version and use\n            // it for state in a closure\n            repeatMode = .times(count - 1)\n        }\n        \n        return closure()\n    }\n}\n```\n\n## [#45 Using dot syntax for static properties and initializers](https://twitter.com/johnsundell/status/931270709824884736)\n\n✒️ Dot syntax is one of my favorite features of Swift. What's really cool is that it's not only for enums, any static method or property can be used with dot syntax - even initializers! Perfect for convenience APIs and default parameters.\n\n```swift\npublic enum RepeatMode {\n    case times(Int)\n    case forever\n}\n\npublic extension RepeatMode {\n    static var never: RepeatMode {\n        return .times(0)\n    }\n\n    static var once: RepeatMode {\n        return .times(1)\n    }\n}\n\nview.perform(animation, repeated: .once)\n\n// To make default parameters more compact, you can even use init with dot syntax\n\nclass ImageLoader {\n    init(cache: Cache = .init(), decoder: ImageDecoder = .init()) {\n        ...\n    }\n}\n```\n\n## [#44 Calling functions as closures with a tuple as parameters](https://twitter.com/johnsundell/status/930103466294435840)\n\n🚀 One really cool aspect of Swift having first class functions is that you can pass any function (or even initializer) as a closure, and even call it with a tuple containing its parameters!\n\n```swift\n// This function lets us treat any \"normal\" function or method as\n// a closure and run it with a tuple that contains its parameters\nfunc call\u003cInput, Output\u003e(_ function: (Input) -\u003e Output, with input: Input) -\u003e Output {\n    return function(input)\n}\n\nclass ViewFactory {\n    func makeHeaderView() -\u003e HeaderView {\n        // We can now pass an initializer as a closure, and a tuple\n        // containing its parameters\n        return call(HeaderView.init, with: loadTextStyles())\n    }\n    \n    private func loadTextStyles() -\u003e (font: UIFont, color: UIColor) {\n        return (theme.font, theme.textColor)\n    }\n}\n\nclass HeaderView {\n    init(font: UIFont, textColor: UIColor) {\n        ...\n    }\n}\n```\n\n## [#43 Enabling static dependency injection](https://twitter.com/johnsundell/status/928630015390027778)\n\n💉 If you've been struggling to test code that uses static APIs, here's a technique you can use to enable static dependency injection without having to modify any call sites:\n\n```swift\n// Before: Almost impossible to test due to the use of singletons\n\nclass Analytics {\n    static func log(_ event: Event) {\n        Database.shared.save(event)\n        \n        let dictionary = event.serialize()\n        NetworkManager.shared.post(dictionary, to: eventURL)\n    }\n}\n\n// After: Much easier to test, since we can inject mocks as arguments\n\nclass Analytics {\n    static func log(_ event: Event,\n                    database: Database = .shared,\n                    networkManager: NetworkManager = .shared) {\n        database.save(event)\n        \n        let dictionary = event.serialize()\n        networkManager.post(dictionary, to: eventURL)\n    }\n}\n```\n\n## [#42 Type inference for lazy properties in Swift 4](https://twitter.com/johnsundell/status/925826172738514945)\n\n🎉 In Swift 4, type inference works for lazy properties and you don't need to explicitly refer to `self`!\n\n```swift\n// Swift 3\n\nclass PurchaseView: UIView {\n    private lazy var buyButton: UIButton = self.makeBuyButton()\n    \n    private func makeBuyButton() -\u003e UIButton {\n        let button = UIButton()\n        button.setTitle(\"Buy\", for: .normal)\n        button.setTitleColor(.blue, for: .normal)\n        return button\n    }\n}\n\n// Swift 4\n\nclass PurchaseView: UIView {\n    private lazy var buyButton = makeBuyButton()\n    \n    private func makeBuyButton() -\u003e UIButton {\n        let button = UIButton()\n        button.setTitle(\"Buy\", for: .normal)\n        button.setTitleColor(.blue, for: .normal)\n        return button\n    }\n}\n```\n\n## [#41 Converting Swift errors to NSError](https://twitter.com/johnsundell/status/923221568175603712)\n\n😎 You can turn any Swift `Error` into an `NSError`, which is super useful when pattern matching with a code 👍. Also, switching on optionals is pretty cool!\n\n```swift\nlet task = urlSession.dataTask(with: url) { data, _, error in\n    switch error {\n    case .some(let error as NSError) where error.code == NSURLErrorNotConnectedToInternet:\n        presenter.showOfflineView()\n    case .some(let error):\n        presenter.showGenericErrorView()\n    case .none:\n        presenter.renderContent(from: data)\n    }\n}\n\ntask.resume()\n```\n\nAlso make sure to check out [Kostas Kremizas' tip](https://twitter.com/kostaskremizas/status/923228453784170497) about how you can pattern match directly against a member of `URLError`.\n\n## [#40 Making UIImage macOS compatible](https://twitter.com/johnsundell/status/915593457082740736)\n\n🖥 Here's an easy way to make iOS model code that uses `UIImage` macOS compatible - like me and [Gui Rambo](https://twitter.com/_inside) discussed on the [Swift by Sundell Podcast](https://swiftbysundell.com/podcast/7).\n\n```swift\n// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif\n\nimport Cocoa\n\n// Step 1: Typealias UIImage to NSImage\ntypealias UIImage = NSImage\n\n// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.\nextension NSImage {\n    var cgImage: CGImage? {\n        var proposedRect = CGRect(origin: .zero, size: size)\n\n        return cgImage(forProposedRect: \u0026proposedRect,\n                       context: nil,\n                       hints: nil)\n    }\n\n    convenience init?(named name: String) {\n        self.init(named: Name(name))\n    }\n}\n\n// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!\nstruct User {\n    let name: String\n    let profileImage: UIImage\n}\n```\n\n## [#39 Internally mutable protocol-oriented APIs](https://twitter.com/johnsundell/status/914069005786341379)\n\n🤖 You can easily define a protocol-oriented API that can only be mutated internally, by using an internal protocol that extends a public one.\n\n```swift\n// Declare a public protocol that acts as your immutable API\npublic protocol ModelHolder {\n    associatedtype Model\n    var model: Model { get }\n}\n\n// Declare an extended, internal protocol that provides a mutable API\ninternal protocol MutableModelHolder: ModelHolder {\n    var model: Model { get set }\n}\n\n// You can now implement the requirements using 'public internal(set)'\npublic class UserHolder: MutableModelHolder {\n    public internal(set) var model: User\n\n    internal init(model: User) {\n        self.model = model\n    }\n}\n```\n\n## [#38 Switching on a set](https://twitter.com/johnsundell/status/906097785883242496)\n\n🎛 You can switch on a set using array literals as cases in Swift! Can be really useful to avoid many `if`/`else if` statements.\n\n```swift\nclass RoadTile: Tile {\n    var connectedDirections = Set\u003cDirection\u003e()\n\n    func render() {\n        switch connectedDirections {\n        case [.up, .down]:\n            image = UIImage(named: \"road-vertical\")\n        case [.left, .right]:\n            image = UIImage(named: \"road-horizontal\")\n        default:\n            image = UIImage(named: \"road\")\n        }\n    }\n}\n```\n\n## [#37 Adding the current locale to cache keys](https://twitter.com/johnsundell/status/900290163376607232)\n\n🌍 When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.\n\n```swift\nfunc cache(_ content: Content, forKey key: String) throws {\n    let data = try wrap(content) as Data\n    let key = localize(key: key)\n    try storage.store(data, forKey: key)\n}\n\nfunc loadCachedContent(forKey key: String) -\u003e Content? {\n    let key = localize(key: key)\n    let data = storage.loadData(forKey: key)\n    return data.flatMap { try? unbox(data: $0) }\n}\n\nprivate func localize(key: String) -\u003e String {\n    return key + \"-\" + Bundle.main.preferredLocalizations[0]\n}\n```\n\n## [#36 Setting up tests to avoid retain cycles with weak references](https://twitter.com/johnsundell/status/899982180776017920)\n\n🚳 Here's an easy way to setup a test to avoid accidental retain cycles with object relationships (like weak delegates \u0026 observers) in Swift:\n\n```swift\nfunc testDelegateNotRetained() {\n    // Assign the delegate (weak) and also retain it using a local var\n    var delegate: Delegate? = DelegateMock()\n    controller.delegate = delegate\n    XCTAssertNotNil(controller.delegate)\n    \n    // Release the local var, which should also release the weak reference\n    delegate = nil\n    XCTAssertNil(controller.delegate)\n}\n```\n\n## [#35 Expressively matching a value against a list of candidates](https://twitter.com/johnsundell/status/899745079987982338)\n\n👨‍🔬 Playing around with an expressive way to check if a value matches any of a list of candidates in Swift:\n\n```swift\n// Instead of multiple conditions like this:\n\nif string == \"One\" || string == \"Two\" || string == \"Three\" {\n\n}\n\n// You can now do:\n\nif string == any(of: \"One\", \"Two\", \"Three\") {\n\n}\n```\n\n*You can find a [gist with the implementation here](https://gist.github.com/JohnSundell/1956ce36b9303eb4bf912da0de9e2844).*\n\n## [#34 Organizing code using extensions](https://twitter.com/johnsundell/status/897186531592556545)\n\n👪 APIs in a Swift extension automatically inherit its access control level, making it a neat way to organize public, internal \u0026 private APIs.\n\n```swift\npublic extension Animation {\n    init(textureNamed textureName: String) {\n        frames = [Texture(name: textureName)]\n    }\n    \n    init(texturesNamed textureNames: [String], frameDuration: TimeInterval = 1) {\n        frames = textureNames.map(Texture.init)\n        self.frameDuration = frameDuration\n    }\n    \n    init(image: Image) {\n        frames = [Texture(image: image)]\n    }\n}\n\ninternal extension Animation {\n    func loadFrameImages() -\u003e [Image] {\n        return frames.map { $0.loadImageIfNeeded() }\n    }\n}\n```\n\n## [#33 Using map to transform an optional into a Result type](https://twitter.com/johnsundell/status/896317661302444033)\n\n🗺 Using `map` you can transform an optional value into an optional `Result` type by simply passing in the enum case.\n\n```swift\nenum Result\u003cValue\u003e {\n    case value(Value)\n    case error(Error)\n}\n\nclass Promise\u003cValue\u003e {\n    private var result: Result\u003cValue\u003e?\n    \n    init(value: Value? = nil) {\n        result = value.map(Result.value)\n    }\n}\n```\n\n## [#32 Assigning to self in struct initializers](https://twitter.com/johnsundell/status/896024128330891264)\n\n👌 It's so nice that you can assign directly to `self` in `struct` initializers in Swift. Very useful when adding conformance to protocols.\n\n```swift\nextension Bool: AnswerConvertible {\n    public init(input: String) throws {\n        switch input.lowercased() {\n        case \"y\", \"yes\", \"👍\":\n            self = true\n        default:\n            self = false\n        }\n    }\n}\n```\n\n## [#31 Recursively calling closures as inline functions](https://twitter.com/johnsundell/status/894580870786539520)\n\n☎️ Defining Swift closures as inline functions enables you to recursively call them, which is super useful in things like custom sequences.\n\n```swift\nclass Database {\n    func records(matching query: Query) -\u003e AnySequence\u003cRecord\u003e {\n        var recordIterator = loadRecords().makeIterator()\n        \n        func iterate() -\u003e Record? {\n            guard let nextRecord = recordIterator.next() else {\n                return nil\n            }\n            \n            guard nextRecord.matches(query) else {\n                // Since the closure is an inline function, it can be recursively called,\n                // in this case in order to advance to the next item.\n                return iterate()\n            }\n            \n            return nextRecord\n        }\n        \n        // AnySequence/AnyIterator are part of the standard library and provide an easy way\n        // to define custom sequences using closures.\n        return AnySequence { AnyIterator(iterate) }\n    }\n}\n```\n\n*[Rob Napier](https://twitter.com/cocoaphony) points out that using the above might cause crashes if used on a large databaset, since Swift has no guaranteed [Tail Call](https://en.wikipedia.org/wiki/Tail_call) Optimization (TCO).*\n\n*[Slava Pestov](https://twitter.com/slava_pestov) also points out that another benefit of inline functions vs closures is that they can have their own generic parameter list.*\n\n## [#30 Passing self to required Objective-C dependencies](https://twitter.com/johnsundell/status/892751766227480576)\n\n🏖 Using lazy properties in Swift, you can pass `self` to required Objective-C dependencies without having to use force-unwrapped optionals.\n\n```swift\nclass DataLoader: NSObject {\n    lazy var urlSession: URLSession = self.makeURLSession()\n    \n    private func makeURLSession() -\u003e URLSession {\n        return URLSession(configuration: .default, delegate: self, delegateQueue: .main)\n    }\n}\n\nclass Renderer {\n    lazy var displayLink: CADisplayLink = self.makeDisplayLink()\n    \n    private func makeDisplayLink() -\u003e CADisplayLink {\n        return CADisplayLink(target: self, selector: #selector(screenDidRefresh))\n    }\n}\n```\n\n## [#29 Making weak or lazy properties readonly](https://twitter.com/johnsundell/status/890906366143078400)\n\n👓 If you have a property in Swift that needs to be `weak` or `lazy`, you can still make it readonly by using `private(set)`.\n\n```swift\nclass Node {\n    private(set) weak var parent: Node?\n    private(set) lazy var children = [Node]()\n\n    func add(child: Node) {\n        children.append(child)\n        child.parent = self\n    }\n}\n```\n\n## [#28 Defining static URLs using string literals](https://twitter.com/johnsundell/status/886876157479616513)\n\n🌏 Tired of using `URL(string: \"url\")!` for static URLs? Make `URL` conform to `ExpressibleByStringLiteral` and you can now simply use `\"url\"` instead.\n\n```swift\nextension URL: ExpressibleByStringLiteral {\n    // By using 'StaticString' we disable string interpolation, for safety\n    public init(stringLiteral value: StaticString) {\n        self = URL(string: \"\\(value)\").require(hint: \"Invalid URL string literal: \\(value)\")\n    }\n}\n\n// We can now define URLs using static string literals 🎉\nlet url: URL = \"https://www.swiftbysundell.com\"\nlet task = URLSession.shared.dataTask(with: \"https://www.swiftbysundell.com\")\n\n// In Swift 3 or earlier, you also have to implement 2 additional initializers\nextension URL {\n    public init(extendedGraphemeClusterLiteral value: StaticString) {\n        self.init(stringLiteral: value)\n    }\n\n    public init(unicodeScalarLiteral value: StaticString) {\n        self.init(stringLiteral: value)\n    }\n}\n```\n\n*To find the extension that adds the `require()` method on `Optional` that I use above, check out [Require](https://github.com/johnsundell/require).*\n\n## [#27 Manipulating points, sizes and frames using math operators](https://twitter.com/johnsundell/status/885486106594115584)\n\n✚ I'm always careful with operator overloading, but for manipulating things like sizes, points \u0026 frames I find them super useful.\n\n```swift\nextension CGSize {\n    static func *(lhs: CGSize, rhs: CGFloat) -\u003e CGSize {\n        return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)\n    }\n}\n\nbutton.frame.size = image.size * 2\n```\n\n*If you like the above idea, check out [CGOperators](https://github.com/JohnSundell/CGOperators), which contains math operator overloads for all Core Graphics' vector types.*\n\n## [#26 Using closure types in generic constraints](https://twitter.com/johnsundell/status/884794185722859520)\n\n🔗 You can use closure types in generic constraints in Swift. Enables nice APIs for handling sequences of closures.\n\n```swift\nextension Sequence where Element == () -\u003e Void {\n    func callAll() {\n        forEach { $0() }\n    }\n}\n\nextension Sequence where Element == () -\u003e String {\n    func joinedResults(separator: String) -\u003e String {\n        return map { $0() }.joined(separator: separator)\n    }\n}\n\ncallbacks.callAll()\nlet names = nameProviders.joinedResults(separator: \", \")\n```\n\n*(If you're using Swift 3, you have to change `Element` to `Iterator.Element`)*\n\n## [#25 Using associated enum values to avoid state-specific optionals](https://twitter.com/johnsundell/status/879427146367848448)\n\n🎉 Using associated enum values is a super nice way to encapsulate mutually exclusive state info (and avoiding state-specific optionals).\n\n```swift\n// BEFORE: Lots of state-specific, optional properties\n\nclass Player {\n    var isWaitingForMatchMaking: Bool\n    var invitingUser: User?\n    var numberOfLives: Int\n    var playerDefeatedBy: Player?\n    var roundDefeatedIn: Int?\n}\n\n// AFTER: All state-specific information is encapsulated in enum cases\n\nclass Player {\n    enum State {\n        case waitingForMatchMaking\n        case waitingForInviteResponse(from: User)\n        case active(numberOfLives: Int)\n        case defeated(by: Player, roundNumber: Int)\n    }\n    \n    var state: State\n}\n```\n\n## [#24 Using enums for async result types](https://twitter.com/johnsundell/status/876920087885877248)\n\n👍 I really like using enums for all async result types, even boolean ones. Self-documenting, and makes the call site a lot nicer to read too!\n\n```swift\nprotocol PushNotificationService {\n    // Before\n    func enablePushNotifications(completionHandler: @escaping (Bool) -\u003e Void)\n    \n    // After\n    func enablePushNotifications(completionHandler: @escaping (PushNotificationStatus) -\u003e Void)\n}\n\nenum PushNotificationStatus {\n    case enabled\n    case disabled\n}\n\nservice.enablePushNotifications { status in\n    if status == .enabled {\n        enableNotificationsButton.removeFromSuperview()\n    }\n}\n```\n\n## [#23 Working on async code in a playground](https://twitter.com/johnsundell/status/876044534458847232)\n\n🏃 Want to work on your async code in a Swift Playground? Just set `needsIndefiniteExecution` to true to keep it running:\n\n```swift\nimport PlaygroundSupport\n\nPlaygroundPage.current.needsIndefiniteExecution = true\n\nDispatchQueue.main.asyncAfter(deadline: .now() + 3) {\n    let greeting = \"Hello after 3 seconds\"\n    print(greeting)\n}\n```\n\nTo stop the playground from executing, simply call `PlaygroundPage.current.finishExecution()`.\n\n## [#22 Overriding self with a weak reference](https://twitter.com/johnsundell/status/874290749386477569)\n\n💦 Avoid memory leaks when accidentially refering to `self` in closures by overriding it locally with a weak reference:\n\n**Swift \u003e= 4.2**\n\n```swift\ndataLoader.loadData(from: url) { [weak self] result in\n    guard let self = self else { \n        return \n    }\n\n    self.cache(result)\n    \n    ...\n```\n\n**Swift \u003c 4.2**\n\n```swift\ndataLoader.loadData(from: url) { [weak self] result in\n    guard let `self` = self else {\n        return\n    }\n\n    self.cache(result)\n    \n    ...\n```\n\nNote that the reason the above currently works is [because of a compiler bug](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/007425.html) (which I hope gets turned into a properly supported feature soon).\n\n## [#21 Using DispatchWorkItem](https://twitter.com/johnsundell/status/868849469558861824)\n\n🕓 Using dispatch work items you can easily cancel a delayed asynchronous GCD task if you no longer need it:\n\n```swift\nlet workItem = DispatchWorkItem {\n    // Your async code goes in here\n}\n\n// Execute the work item after 1 second\nDispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)\n\n// You can cancel the work item if you no longer need it\nworkItem.cancel()\n```\n\n## [#20 Combining a sequence of functions](https://twitter.com/johnsundell/status/865855870294523904)\n\n➕ While working on a new Swift developer tool (to be open sourced soon 😉), I came up with a pretty neat way of organizing its sequence of operations, by combining their functions into a closure:\n\n```swift\ninternal func +\u003cA, B, C\u003e(lhs: @escaping (A) throws -\u003e B,\n                         rhs: @escaping (B) throws -\u003e C) -\u003e (A) throws -\u003e C {\n    return { try rhs(lhs($0)) }\n}\n\npublic func run() throws {\n    try (determineTarget + build + analyze + output)()\n}\n```\n\n*If you're familiar with the functional programming world, you might know the above technique as the [pipe operator](http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/) (thanks to [Alexey Demedreckiy](https://twitter.com/DAlooG) for pointing this out!)*\n\n## [#19 Chaining optionals with map() and flatMap()](https://twitter.com/johnsundell/status/864130284140318720)\n\n🗺 Using `map()` and `flatMap()` on optionals you can chain multiple operations without having to use lengthy `if lets` or `guards`:\n\n```swift\n// BEFORE\n\nguard let string = argument(at: 1) else {\n    return\n}\n\nguard let url = URL(string: string) else {\n    return\n}\n\nhandle(url)\n\n// AFTER\n\nargument(at: 1).flatMap(URL.init).map(handle)\n```\n\n## [#18 Using self-executing closures for lazy properties](https://twitter.com/johnsundell/status/863073311718338561)\n\n🚀 Using self-executing closures is a great way to encapsulate lazy property initialization:\n\n```swift\nclass StoreViewController: UIViewController {\n    private lazy var collectionView: UICollectionView = {\n        let layout = UICollectionViewFlowLayout()\n        let view = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)\n        view.delegate = self\n        view.dataSource = self\n        return view\n    }()\n    \n    override func viewDidLoad() {\n        super.viewDidLoad()\n        view.addSubview(collectionView)\n    }\n}\n```\n\n## [#17 Speeding up Swift package tests](https://twitter.com/johnsundell/status/862721700584189953)\n\n⚡️ You can speed up your Swift package tests using the `--parallel` flag. For [Marathon](https://github.com/johnsundell/marathon), the tests execute 3 times faster that way!\n\n```\nswift test --parallel\n```\n\n## [#16 Avoiding mocking UserDefaults](https://twitter.com/johnsundell/status/855713943809032192)\n\n🛠 Struggling with mocking `UserDefaults` in a test? The good news is: you don't need mocking - just create a real instance:\n\n```swift\nclass LoginTests: XCTestCase {\n    private var userDefaults: UserDefaults!\n    private var manager: LoginManager!\n    \n    override func setUp() {\n        super.setup()\n        \n        userDefaults = UserDefaults(suiteName: #file)\n        userDefaults.removePersistentDomain(forName: #file)\n        \n        manager = LoginManager(userDefaults: userDefaults)\n    }\n}\n```\n\n## [#15 Using variadic parameters](https://twitter.com/johnsundell/status/854365916716572672)\n\n👍 Using variadic parameters in Swift, you can create some really nice APIs that take a list of objects without having to use an array:\n\n```swift\nextension Canvas {\n    func add(_ shapes: Shape...) {\n        shapes.forEach(add)\n    }\n}\n\nlet circle = Circle(center: CGPoint(x: 5, y: 5), radius: 5)\nlet lineA = Line(start: .zero, end: CGPoint(x: 10, y: 10))\nlet lineB = Line(start: CGPoint(x: 0, y: 10), end: CGPoint(x: 10, y: 0))\n\nlet canvas = Canvas()\ncanvas.add(circle, lineA, lineB)\ncanvas.render()\n```\n\n## [#14 Referring to enum cases with associated values as closures](https://twitter.com/johnsundell/status/848951678288228352)\n\n😮 Just like you can refer to a Swift function as a closure, you can do the same thing with enum cases with associated values:\n\n```swift\nenum UnboxPath {\n    case key(String)\n    case keyPath(String)\n}\n\nstruct UserSchema {\n    static let name = key(\"name\")\n    static let age = key(\"age\")\n    static let posts = key(\"posts\")\n    \n    private static let key = UnboxPath.key\n}\n```\n\n## [#13 Using the === operator to compare objects by instance](https://twitter.com/johnsundell/status/847468284198797313)\n\n📈 The `===` operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:\n\n```swift\nprotocol InstanceEquatable: class, Equatable {}\n\nextension InstanceEquatable {\n    static func ==(lhs: Self, rhs: Self) -\u003e Bool {\n        return lhs === rhs\n    }\n}\n\nextension Enemy: InstanceEquatable {}\n\nfunc testDestroyingEnemy() {\n    player.attack(enemy)\n    XCTAssertTrue(player.destroyedEnemies.contains(enemy))\n}\n```\n\n## [#12 Calling initializers with dot syntax and passing them as closures](https://twitter.com/johnsundell/status/845560409126027264)\n\n😎 Cool thing about Swift initializers: you can call them using dot syntax and pass them as closures! Perfect for mocking dates in tests.\n\n```swift\nclass Logger {\n    private let storage: LogStorage\n    private let dateProvider: () -\u003e Date\n    \n    init(storage: LogStorage = .init(), dateProvider: @escaping () -\u003e Date = Date.init) {\n        self.storage = storage\n        self.dateProvider = dateProvider\n    }\n    \n    func log(event: Event) {\n        storage.store(event: event, date: dateProvider())\n    }\n}\n```\n\n## [#11 Structuring UI tests as extensions on XCUIApplication](https://twitter.com/johnsundell/status/844945775088013312)\n\n📱 Most of my UI testing logic is now categories on `XCUIApplication`. Makes the test cases really easy to read:\n\n```swift\nfunc testLoggingInAndOut() {\n    XCTAssertFalse(app.userIsLoggedIn)\n    \n    app.launch()\n    app.login()\n    XCTAssertTrue(app.userIsLoggedIn)\n    \n    app.logout()\n    XCTAssertFalse(app.userIsLoggedIn)\n}\n\nfunc testDisplayingCategories() {\n    XCTAssertFalse(app.isDisplayingCategories)\n    \n    app.launch()\n    app.login()\n    app.goToCategories()\n    XCTAssertTrue(app.isDisplayingCategories)\n}\n```\n\n## [#10 Avoiding default cases in switch statements](https://twitter.com/johnsundell/status/844608407718051847)\n\n🙂 It’s a good idea to avoid “default” cases when switching on Swift enums - it’ll “force you” to update your logic when a new case is added:\n\n```swift\nenum State {\n    case loggedIn\n    case loggedOut\n    case onboarding\n}\n\nfunc handle(_ state: State) {\n    switch state {\n    case .loggedIn:\n        showMainUI()\n    case .loggedOut:\n        showLoginUI()\n    // Compiler error: Switch must be exhaustive\n    }\n}\n```\n\n## [#9 Using the guard statement in many different scopes](https://twitter.com/johnsundell/status/844262618630148098)\n\n💂 It's really cool that you can use Swift's 'guard' statement to exit out of pretty much any scope, not only return from functions:\n\n```swift\n// You can use the 'guard' statement to...\n\nfor string in strings {\n    // ...continue an iteration\n    guard shouldProcess(string) else {\n        continue\n    }\n    \n    // ...or break it\n    guard !shouldBreak(for: string) else {\n        break\n    }\n    \n    // ...or return\n    guard !shouldReturn(for: string) else {\n        return\n    }\n    \n    // ..or throw an error\n    guard string.isValid else {\n        throw StringError.invalid(string)\n    }\n    \n    // ...or exit the program\n    guard !shouldExit(for: string) else {\n        exit(1)\n    }\n}\n```\n\n## [#8 Passing functions \u0026 operators as closures](https://twitter.com/johnsundell/status/843771235897098240)\n\n❤️ Love how you can pass functions \u0026 operators as closures in Swift. For example, it makes the syntax for sorting arrays really nice!\n\n```swift\nlet array = [3, 9, 1, 4, 6, 2]\nlet sorted = array.sorted(by: \u003c)\n```\n\n## [#7 Using #function for UserDefaults key consistency](https://twitter.com/johnsundell/status/842058888371421185)\n\n🗝 Here's a neat little trick I use to get UserDefault key consistency in Swift (#function expands to the property name in getters/setters). Just remember to write a good suite of tests that'll guard you against bugs when changing property names.\n\n```swift\nextension UserDefaults {\n    var onboardingCompleted: Bool {\n        get { return bool(forKey: #function) }\n        set { set(newValue, forKey: #function) }\n    }\n}\n```\n\n## [#6 Using a name already taken by the standard library](https://twitter.com/johnsundell/status/839209426015891456)\n\n📛 Want to use a name already taken by the standard library for a nested type? No problem - just use `Swift.` to disambiguate:\n\n```swift\nextension Command {\n    enum Error: Swift.Error {\n        case missing\n        case invalid(String)\n    }\n}\n```\n\n## [#5 Using Wrap to implement Equatable](https://twitter.com/johnsundell/status/835860744176553984)\n\n📦 Playing around with using [Wrap](https://github.com/johnsundell/wrap) to implement `Equatable` for any type, primarily for testing:\n\n```swift\nprotocol AutoEquatable: Equatable {}\n\nextension AutoEquatable {\n    static func ==(lhs: Self, rhs: Self) -\u003e Bool {\n        let lhsData = try! wrap(lhs) as Data\n        let rhsData = try! wrap(rhs) as Data\n        return lhsData == rhsData\n    }\n}\n```\n\n## [#4 Using typealiases to reduce the length of method signatures](https://twitter.com/johnsundell/status/823554020639916033)\n\n📏 One thing that I find really useful in Swift is to use typealiases to reduce the length of method signatures in generic types:\n\n```swift\npublic class PathFinder\u003cObject: PathFinderObject\u003e {\n    public typealias Map = Object.Map\n    public typealias Node = Map.Node\n    public typealias Path = PathFinderPath\u003cObject\u003e\n    \n    public static func possiblePaths(for object: Object, at rootNode: Node, on map: Map) -\u003e Path.Sequence {\n        return .init(object: object, rootNode: rootNode, map: map)\n    }\n}\n```\n\n## [#3 Referencing either external or internal parameter name when writing docs](https://twitter.com/johnsundell/status/823131585830645760)\n\n📖 You can reference either the external or internal parameter label when writing Swift docs - and they get parsed the same:\n\n```swift\n// EITHER:\n\nclass Foo {\n    /**\n    *   - parameter string: A string\n    */\n    func bar(with string: String) {}\n}\n\n// OR:\n\nclass Foo {\n    /**\n    *   - parameter with: A string\n    */\n    func bar(with string: String) {}\n}\n```\n\n## [#2 Using auto closures](https://twitter.com/johnsundell/status/822097067648700418)\n\n👍 Finding more and more uses for auto closures in Swift. Can enable some pretty nice APIs:\n\n```swift\nextension Dictionary {\n    mutating func value(for key: Key, orAdd valueClosure: @autoclosure () -\u003e Value) -\u003e Value {\n        if let value = self[key] {\n            return value\n        }\n        \n        let value = valueClosure()\n        self[key] = value\n        return value\n    }\n}\n```\n\n## [#1 Namespacing with nested types](https://twitter.com/johnsundell/status/821828733107634176)\n\n🚀 I’ve started to become a really big fan of nested types in Swift. Love the additional namespacing it gives you!\n\n```swift\npublic struct Map {\n    public struct Model {\n        public let size: Size\n        public let theme: Theme\n        public var terrain: [Position : Terrain.Model]\n        public var units: [Position : Unit.Model]\n        public var buildings: [Position : Building.Model]\n    }\n    \n    public enum Direction {\n        case up\n        case right\n        case down\n        case left\n    }\n    \n    public struct Position {\n        public var x: Int\n        public var y: Int\n    }\n    \n    public enum Size: String {\n        case small = \"S\"\n        case medium = \"M\"\n        case large = \"L\"\n        case extraLarge = \"XL\"\n    }\n}\n```\n","funding_links":[],"categories":["Guides","Others","Third party Guides [🔝](#readme)","HarmonyOS","Swift-Tips"],"sub_categories":["Third party Guides","Windows Manager","Swift之struct二进制大小分析"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJohnSundell%2FSwiftTips","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FJohnSundell%2FSwiftTips","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FJohnSundell%2FSwiftTips/lists"}