Created
February 10, 2020 13:53
-
-
Save DevAndArtist/8267a7db584d6dac2b15adb012633d23 to your computer and use it in GitHub Desktop.
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
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