Created
May 27, 2020 15:46
-
-
Save markiv/63f4cac8a8442f6d33f068e853d8b4a1 to your computer and use it in GitHub Desktop.
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
/* | |
If you've ever wished you could calculate or evaluate something inside your #SwiftUI view's body without repeating yourself, try this pseudo-view helper. | |
You can now compute multiple values in tuples, call helper functions or print debug expressions. | |
*/ | |
struct Calculate<Content: View, Value>: View { | |
let calculation: () -> Value | |
let content: (Value) -> Content | |
init( | |
_ calculation: @autoclosure @escaping () -> Value, | |
@ViewBuilder content: @escaping (Value) -> Content | |
) { | |
self.calculation = calculation | |
self.content = content | |
} | |
var body: some View { | |
content(calculation()) | |
} | |
} | |
struct ContentView: View { | |
var body: some View { | |
GeometryReader { geometry in | |
Calculate(geometry.size.width / 3) { radius in | |
Circle().frame(width: radius) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment