Initialization order of members

(Maik) #1

Is there any specific reason why I can't do this:

class TestClass {
    private let a = 5
    private let b = 2
    private let c = a + b // would work in java

But I can do this:

class TestClass {
    private let a = 5
    private let b = 2
    private lazy var c = a + b

A difference for example is that I can reassign c in the second case, but I can't in the first case.

Is there any specific reason why swift does not (and probably will never) support that?
It would will work if I add the static keyword. While I understand why it might be easier for a static context I'm wondering why there was made a difference.


It works for static members because all static members are initialized lazily. The lazy keyword is redundant for such declarations.

(Maik) #3

Thanks for your reply. This might show better, what I mean.

private let a = 5
private let b = 2
private lazy var c = a + b
 // the compiler can know the values of a and b. And could imply "lazy let"
private let d = a + b

private static let staticA = 5
private static let staticB = 2
// since static is already lazy: private static lazy var staticC = staticA + staticB
private static var staticC = staticA + staticB
 // not equal to staticC, since it is not possible to reassign staticD
private static let staticD = staticA + staticB

Why was the decision made that staticD is possible while d is not possible?

(Jordan Rose) #4

It's possible for the compiler to support this, sure, but it would only work when using let properties that have initial values. Otherwise it's unclear how the computation would sequence relative to explicit assignments in the initializer.

(Maik) #5

I don't know how swift handles initialization of members. I think Java for example did just copy all members inside the constructor. I don't know if there is anything bad at this approach. For now do not have any arguments against it.

If swift would take the order of declaration into account it should be possible. Its possible inside functions, so for now I do not see why it shouldn't be possible for members. Thats why I thought that there has to be a reason why it's not possible. It seems like there was made an explicit choice.

This might be just syntactic sugar since this can be archived using initializer, but I might have to duplicate code for multiple initializer.

(Jordan Rose) #6

Sorry for not being clear. It was an explicit choice not to support this because it's simpler to say "properties can't refer to other properties in their initial value" than to say "properties can refer to some properties but not others in their initial value". That decision could be changed, of course, through the Swift Evolution Process.

1 Like
(Maik) #7

Thanks, that is exactly what I wanted to know! I’ll think about a proposal.