[swift-users] lazy initialisation
Mark Dalrymple
markd at borkware.com
Mon Jul 4 14:12:25 CDT 2016
Here's the one I started with:
lazy var c:Int = {return a*b}()
and ended up with:
lazy var c:Int = {return self.a * self.b}()
It's in a closure, so need to explicitly reference self.
Cheers,
++md
On Mon, Jul 4, 2016 at 3:04 PM, J.E. Schotsman via swift-users <
swift-users at swift.org> wrote:
>
> > On 04 Jul 2016, at 19:21, Zhao Xin <owenzx at gmail.com> wrote:
> >
> > You'd better sharing some of you code here first.
>
> For example, consider this:
>
> class TestStruct1
> {
> let a = 10
> let b = 20
> let c:Int = {return self.a*self.b}()
> }
>
> Of course this is a trivial example. In reality the calculation of c from
> a and b might take longer.
>
> Since this is not allowed I try
>
> struct TestStruct2
> {
> let a = 10
> let b = 20
> lazy var c:Int = {return a*b}()
> }
>
> Not allowed either even though neither a nor b is lazy.
> I have to do
>
> struct TestStruct3
> {
> let a = 10
> let b = 20
>
> private var cInitialized = false
> private var _c = 0
> var c:Int
> {
> mutating get {
> if !cInitialized
> {
> _c = a*b
> cInitialized = true
> }
> return _c }
> }
> }
>
> BTW I pasted Mark’s code in a playground and it compiles indeed.
> What’s the difference?
>
> Jan E.
>
>
> _______________________________________________
> 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/20160704/a2369d44/attachment.html>
More information about the swift-users
mailing list