0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ViewBuilderを理解するためresultBuilderを独自実装

Posted at
playground.swift
@resultBuilder
public struct AdderBuilder {
    //supports DSL in block
    public static func buildBlock(_ components: Int...) -> Int {
        components.reduce(0, +)
    }
    
    //supports "if" statement without "else"
    public static func buildOptional(_ component: Int?) -> Int{
        return component ?? 0
    }
    
    //supports "if else" statement
    public static func buildEither(first component: Int) -> Int {
        return component
    }
    public static func buildEither(second component : Int) -> Int{
        return component
    }
    
    //supports "for in" statement
    public static func buildArray(_ components: [Int]) -> Int{
        return components.reduce(0, +)
    }

}

func blockAdder(@AdderBuilder block:()->Int)->Int{
    return block()
}

        
let sum = blockAdder{//buildBlock()
    0
    1
    if 0<1 {//buildOptional()
        2
    }
    
    if 0<1{//buildEither(first:)
        3
    }else{//buildEither(first:)
        4
    }
    
    for _ in 0...2 {//buildArray
        5
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?