Last active
June 23, 2022 09:03
-
-
Save doozMen/eb66de6ad51afd2170885581c66061c8 to your computer and use it in GitHub Desktop.
ResultBuilder for a Dictionary in > Swift 5.4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DictionaryBuilder.swift | |
// | |
// From blog of alejandrom: https://alejandromp.com/blog/better-dictionary-literals-with-swift-result-builders/ | |
// | |
import Foundation | |
/// Based on https://alejandromp.com/blog/better-dictionary-literals-with-swift-result-builders/ | |
/// | |
/// Run following unit test in a test target to understand its use. | |
/// ```swift | |
/// func testBuild() { | |
/// func make(include: Bool) -> [String: Any] { | |
/// Dictionary<String, Any> { | |
/// ["foo": 69] | |
/// if include { | |
/// ["bar": 78] | |
/// } | |
/// ["end": "HelloWorld"] | |
/// } | |
/// } | |
/// | |
/// let dictNoBar = make(include: false) | |
/// XCTAssertEqual(dictNoBar["foo"] as? Int, 69) | |
/// XCTAssertNil(dictNoBar["bar"]) | |
/// XCTAssertEqual(dictNoBar["end"] as? String, "HelloWorld") | |
/// | |
/// let dictBar = make(include: true) | |
/// XCTAssertNotNil(dictBar["bar"]) | |
/// } | |
/// ``` | |
@resultBuilder | |
struct DictionaryBuilder<Key: Hashable, Value> { | |
static func buildBlock(_ dictionaries: Dictionary<Key, Value>...) -> Dictionary<Key, Value> { | |
dictionaries.reduce(into: [:]) { | |
$0.merge($1) { _, new in new } | |
} | |
} | |
static func buildOptional(_ dictionary: Dictionary<Key, Value>?) -> Dictionary<Key, Value> { | |
dictionary ?? [:] | |
} | |
} | |
extension Dictionary { | |
init(@DictionaryBuilder<Key, Value> build: () -> Dictionary) { | |
self = build() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @alexito4 for this nice simple resultbuilder explained in your blog https://alejandromp.com/blog/better-dictionary-literals-with-swift-result-builders/. For future reference for myself I put it in this gist.