Skip to content

Instantly share code, notes, and snippets.

@markiv
Created May 27, 2020 15:46
Show Gist options
  • Save markiv/63f4cac8a8442f6d33f068e853d8b4a1 to your computer and use it in GitHub Desktop.
Save markiv/63f4cac8a8442f6d33f068e853d8b4a1 to your computer and use it in GitHub Desktop.
/*
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