Created
June 16, 2019 13:02
-
-
Save ilyapuchka/4c59801ff506da885d5d4509ff32c4cc to your computer and use it in GitHub Desktop.
FunctionBuilders
This file contains hidden or 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
func stringify(@StringBuilder _ value: () -> Stringified) { | |
print(value().value) | |
} | |
struct Stringified { | |
let value: String | |
init(_ value: String) { | |
self.value = "stringified " + value | |
} | |
} | |
@_functionBuilder | |
struct StringBuilder { | |
static func buildBlock() -> Stringified { | |
return Stringified("empty") | |
} | |
} | |
extension StringBuilder { | |
static func buildBlock(_ value: String) -> Stringified { | |
return Stringified("string \(value)") | |
} | |
static func buildBlock(_ value: String...) -> Stringified { | |
return Stringified("string \(value.joined(separator: ","))") | |
} | |
} | |
stringify { | |
"1" | |
"2" | |
} | |
// stringified string 1,2 | |
extension StringBuilder { | |
static func buildBlock(_ value: Int) -> Stringified { | |
return Stringified("int \(value)") | |
} | |
static func buildBlock(_ value: Int...) -> Stringified { | |
return Stringified("int \(value.map(String.init).joined(separator: ","))") | |
} | |
} | |
stringify { | |
1 | |
2 | |
} | |
// stringified int 1,2 | |
extension StringBuilder { | |
static func buildBlock<T>(_ value: T) -> Stringified { | |
return Stringified("generic \(value)") | |
} | |
static func buildBlock<T>(_ value: T...) -> Stringified { | |
return Stringified("generic \(value.map({ "\($0)" }).joined(separator: ","))") | |
} | |
} | |
stringify { | |
true | |
false | |
} | |
// Following code does not compile | |
// stringified generic true,false | |
stringify { | |
} | |
// Cannot convert value of type '() -> ()' to expected argument type '() -> Stringified' | |
// Expected "stringified " | |
stringify { | |
"1" | |
} | |
// Cannot convert value of type 'String' to closure result type 'Stringified' | |
// Expected "stringified 1" | |
stringify { | |
1 | |
} | |
// Cannot convert value of type 'Int' to closure result type 'Stringified' | |
// Expected "stringified 1" | |
stringify { | |
true | |
} | |
// Cannot convert value of type 'Bool' to closure result type 'Stringified' | |
// Expected "stringified true" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment