Skip to content

Instantly share code, notes, and snippets.

@DevAndArtist
Created February 10, 2020 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevAndArtist/8267a7db584d6dac2b15adb012633d23 to your computer and use it in GitHub Desktop.
Save DevAndArtist/8267a7db584d6dac2b15adb012633d23 to your computer and use it in GitHub Desktop.
struct PKey: PreferenceKey {
static var defaultValue: Int?
static func reduce(value: inout Int?, nextValue: () -> Int?) {
print(#function, "value:", value as Any, "nextValue:", nextValue() as Any)
value = nextValue()
}
}
struct ContentView: View {
let condition = true
var body: some View {
VStack
.init {
Text("A")
.anchorPreference(
key: PKey.self,
value: .bounds,
transform: { _ in 42 }
)
// `Optional` view with `.some(...)` case.
Color?.some(.red)
// This triggers yet another call to `reduce`
if condition {
Circle()
}
// This is a true NOP
if condition == false {
Rectangle()
}
// This does not trigger `reduce`
Color?.none
// This triggers another call to `reduce`
Circle?.some(Circle())
}
.overlayPreferenceValue(PKey.self) { value -> Text in
Text("Test").foregroundColor(Color.green)
}
}
}
// UNEPEXTED OUTPUT:
// reduce(value:nextValue:) value: Optional(42) nextValue: nil
// reduce(value:nextValue:) value: nil nextValue: nil
// reduce(value:nextValue:) value: nil nextValue: nil
// EXPECTED BEHAVIOR:
// `reduce` should not be called even once in this example.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment