โญResult Builders

Swift โŸฉ Attributes โŸฉ

Swift 5.4 Result builders were first introduced as a semi-official language feature called โ€œfunction buildersโ€ as part of the Swift 5.1 release. Xcode 12.5

those buildEither() methods also enable switch statements to be used within result builder contexts, without requiring any additional build methods. ๐Ÿ‘‰ Sundell

๐Ÿ‘‰paiza.io

@resultBuilder
struct StringBuilder {

    // โญ๏ธ (mandantory)
    static func buildBlock(_ parts: String...) -> String {
        parts.joined(separator: "\n")
    }
    
    // โญ๏ธ support `if...else...` statement
    static func buildEither(first part: String) -> String {
        return part
    }

    static func buildEither(second part: String) -> String {
        return part
    }
    
    // โญ๏ธ support `for...in` loop
    static func buildArray(_ parts: [String]) -> String {
        parts.joined(separator: ", ")
    }
}

// โญ๏ธ applied on `func`
@StringBuilder func s1() -> String {
    "Why settle for a Duke"
    "when you can have"
    "a Prince?"
}

// โญ๏ธ applied on `var`
@StringBuilder var s2: String {
    "Why settle for a Duke"
    "when you can have"
    "a Prince?"
}

// โญ๏ธ translated by complier to:
// ------------------------------
// StringBuilder.buildBlock(
//     "Why settle for a Duke",
//     "when you can have",
//     "a Prince?"
// )
// ------------------------------

print(s1())
print(s2)
// Why settle for a Duke
// when you can have
// a Prince?

@StringBuilder var s3: String {

    "Why settle for a Duke"
    "when you can have"

    // โญ๏ธ supported by `buildEither(first:)` / `buildEither(second:)`
    if .random() { "a Frog?" } 
    else { "a King?" }
}

print(s3)

@StringBuilder var countDown: String {

    // โญ๏ธ supported by `buildArray(_:)`
    for i in (0...10).reversed() { "\(i)โ€ฆ" }

    "Lift off!"
}

print(countDown)
// 10โ€ฆ, 9โ€ฆ, 8โ€ฆ, 7โ€ฆ, 6โ€ฆ, 5โ€ฆ, 4โ€ฆ, 3โ€ฆ, 2โ€ฆ, 1โ€ฆ, 0โ€ฆ
// Lift off!

Last updated