[swift-users] Can you use @autoclosure in a setter?
Slava Pestov
spestov at apple.com
Mon Sep 11 17:07:14 CDT 2017
You can have valueSource store a closure that captures the autoclosure value. For example,
set {
valueSource = { newValue }
}
Slava
> On Sep 11, 2017, at 11:04 AM, Nevin Brackett-Rozinsky via swift-users <swift-users at swift.org> wrote:
>
> Hi, quick question here:
>
> I have a class with a property that needs to be really *really* lazy. So lazy, in fact, that when you assign to that property, the class actually stores a closure of what you assigned, which is only evaluated if and when you actually attempt to read the property.
>
> Simplified:
>
> class Foo {
> private var valueSource: () -> Bar
> private var valueCache: Bar?
>
> init(_ v: @escaping @autoclosure () -> Bar) {
> valueSource = v
> }
>
> var value: Bar {
> get {
> if let v = valueCache { return v }
> let w = valueSource()
> valueCache = w
> return w
> }
> set {
> /* ??? */
> }
> }
>
> // I want this function's logic to go in the setter above
> func setValue(_ v: @escaping @autoclosure () -> Bar) {
> valueSource = v
> valueCache = nil
> }
> }
>
> The goal is to be able to write things like “someFoo.value = bar1 / bar2” (or even more complex expressions) and not evaluate them until/unless the result is actually needed.
>
> Currently I am using “someFoo.setValue( bar1 / bar2 )”, which is not nearly as ergonomic as the assignment syntax. So, is there a way to make this work?
>
> Nevin
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170911/08cb5920/attachment.html>
More information about the swift-users
mailing list