[swift-users] lazy initialisation

J.E. Schotsman jeschot at xs4all.nl
Mon Jul 4 14:04:12 CDT 2016


> 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.




More information about the swift-users mailing list