Created
September 21, 2022 15:26
-
-
Save eliperkins/7cc620b56e700b4e9343c32d0a3eb115 to your computer and use it in GitHub Desktop.
Swift autoclosure "lazy" evaluation
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 SomeStruct { | |
init(someReallyExpensiveValue: @autoclosure () -> Int) { | |
print("really expensive") | |
Thread.sleep(forTimeInterval: TimeInterval(someReallyExpensiveValue() * 1)) | |
} | |
init(someEvenMoreExpensiveValue: @autoclosure () -> Int) { | |
print("even more expensive") | |
Thread.sleep(forTimeInterval: TimeInterval(someEvenMoreExpensiveValue() * 5)) | |
} | |
} | |
func someFunction( | |
a: @autoclosure () -> SomeStruct, | |
b: @autoclosure () -> SomeStruct, | |
useA: Bool | |
) { | |
if useA { | |
print(a()) | |
} else { | |
print(b()) | |
} | |
} | |
someFunction(a: .init(someReallyExpensiveValue: 1), b: .init(someEvenMoreExpensiveValue: 1), useA: true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment