Can I rely on the order of property initialization?

Can I trust on properties with an initial value to always be initialized in the same order?

E.g. take the following code:

import Foundation

@propertyWrapper
struct Printed<T> {
    var wrappedValue: T
    
    init(wrappedValue: T) {
        print(wrappedValue)
        self.wrappedValue = wrappedValue
    }
}

struct MyStruct {
    @Printed var one = 1
    @Printed var two = 2
    @Printed var three = 3
    @Printed var four = 4
    @Printed var five = 5

    init(override: Int) {
	_five = Printed(wrappedValue: override)	
    }
}

_ = MyStruct(override: 100)

For me, this always prints 1, 2, 3, 4, 5, 100. Can I rely on that, or could the compiler (on some platform, with some optimization, or even in a certain context in which the MyStruct initializer is called) decide to mix up the order of initialization for the initial values 1 to 5? Is something like that considered part of the language's interface and thus covered by stability guarantees, or could this change with every version?

In case the compiler is allowed to change that order, under what circumstances does it do so?

1 Like

Never fear, side effects like print in initializers are ordered. It's only side effects in different deinits that are unordered.

That's great news! Thanks a lot for the quick response👍🏻

I think Andrew didn't give a full answer to Max's question?

I think print in the same thread are ordered (thought it may be buffered) in all the OS that I know about. For the deinit case, I suppose it's because deinit is unordered and so are the print call in different deinit.

But what Max asked was not this. It's about property initialization order. I doubt if that's part of the language spec. Perhaps it's more safe to implement your own mechanism to achieve that behavior outside initialization process? Just my thoughts.

For my use-case the side effect would be appending a value to a static Array variable (on the same thread), so I guess that would be covered by @Andrew_Trick 's answer?

Please to see your question, I think i have same question but now it will be solved.
Thanks to all community member for sharing your helpful suggestion's.

Writing to a static array (global variable) would be reliably ordered just like a print statement.

I can tell you that compiler optimization will not reorder these side effects. I cannot tell you whether initialization order is formally guaranteed by the language, but I personally don't think it would be reasonable for any implementation to break that expectation.

Ok, I guessed so, but before I would invest time into it I wanted to make sure its not all wasted. Thanks @Andrew_Trick that answer is totally fine for me!

This post was flagged by the community and is temporarily hidden.

Terms of Service

Privacy Policy

Cookie Policy