# Recommended way to initialise a mandatory property in a loop?

**URL:** <https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280>\
**Category:** Using Swift\
**Created:** [January 5, 2024, 12:26am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280 "2024-01-05T00:26:04Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![ffetc](https://avatars.discourse-cdn.com/v4/letter/f/5e9695/32.png) [@ffetc](https://forums.swift.org/u/ffetc)\
**Post date:** [January 5, 2024, 12:26am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/1 "2024-01-05T00:26:04Z")

</div>

This is a very beginner question.

How do you usually deal with initialising a mandatory (`let`) property of a struct, in a loop or other iterative process?

I attempted to write something (approximately) of the form

```swift
struct Bing {
    let bang: String

    init() {
        while true {
            // do something iterative

            if /* some condition */ {
                bang = "bong"
                break
            }
        }

    }
}

```

hoping that the compiler would be able to analyse the loop exit conditions and determine that the variable must always be initialised, but apparently not, and I get the expected `error: return from initializer without initializing all stored properties`.

In a language with loop expressions, I'd tackle this problem that way, yielding / returning the value from the loop: `bang = while true { ...`

What would you suggest doing in Swift?

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 5, 2024, 1:03am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/2 "2024-01-05T01:03:39Z")

</div>

> [@ffetc](#):
>
> hoping that the compiler would be able to analyse the loop exit conditions and determine that the variable must always be initialised, but apparently not

No, that would be equivalent to solving the halting problem, while compiler can't do even this:

```swift
func foo(_ condition: Bool) -> Int {
    let x: Int
    if condition { x = 42 }
    if !condition { x = 24 } // 🛑 Immutable value 'x' may only be initialized once
    return x // 🛑 Constant 'x' used before being initialized
}

```

> [@ffetc](#):
>
> What would you suggest doing in Swift?

Do you promise to "break" only when "bang" is assigned? And not assign "bang" more than once? Compiler won't be able to check, so it's up to you.

Typically you'd do one of these:

```swift
1. var bang: String = ""

```

and then reassign (exactly once), compiler will not check that you did.

```swift
2. var bang: String!

```

and then reassign (exactly once). compiler will still not check that you did, but you'd at least crash in runtime if you forgot to assign at least once.

```swift
3. var bang: String! { // "set-only-once" property
    didSet {
        precondition(oldValue == nil && bang != nil)
    }
}

```

this will crash at runtime in cases when you reassign the property more than once

```swift
    4. 
    bang = f(...)
    func f(....) {
        while true {
            if ... { return "..." }
            ....
        }
    }

```

i.e. refactor the while loop into a (local) function. This one won't work in "init" though.

> [@ffetc](#):
>
> In a language with loop expressions

This reminds me we haven't finished yet with the [multi-statement-if-switch-do-expressions pitch](https://forums.swift.org/t/pitch-multi-statement-if-switch-do-expressions). Loops were not part of that pitch but were brought up during the discussion.

---

<div class="post-metadata">

**Author:** ![ffetc](https://avatars.discourse-cdn.com/v4/letter/f/5e9695/32.png) [@ffetc](https://forums.swift.org/u/ffetc)\
**Post date:** [January 5, 2024, 1:57am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/3 "2024-01-05T01:57:49Z")

</div>

Thanks for the detailed answer! I'd considered 1 and 4 as options, but here I think 2 makes the most sense, as a balance of readability, obviousness, and safety (and I didn't know about that syntax).

Notably, 1 doesn't seem to work well for types without a simple "default" instance (something more complicated than `String`).

> [@tera](#):
>
> No, that would be equivalent to solving the halting problem

Yes, I'm fully aware that compilers can't _in general_ reason about loop exits, but LLVM is pretty good at figuring out simple ones later on, during optimisation, and when warning about dead code. I wonder how infeasible it'd be to do some of that transformation early enough that semantic analysis like this could benefit from it?

Anyway, that's no criticism of Swift, most languages have the exact same issue with code like that.

> [@tera](#):
>
> This reminds me we haven't finished yet with the [multi-statement-if-switch-do-expressions pitch](https://forums.swift.org/t/pitch-multi-statement-if-switch-do-expressions). Loops were not part of that pitch but were brought up during the discussion.

Neat!

I'll confess, compared to a language designed around everything being an expression to begin with (say, Rust, or a fully functional language like Haskell), the proposed syntaxes seem... really clunky.

But maybe still worth doing, including for loops - for cases just like this. Formalising the idea of a loop "producing" a value lets the compiler check all the things you want it to check.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [January 5, 2024, 2:14am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/4 "2024-01-05T02:14:05Z")

</div>

> [@tera](#):
>
> No, that would be equivalent to solving the halting problem,

`while true` is already special cased to be known as an infinite loop for unreachable code analysis, so I'd call it a bug that we don't handle it as such for definite initialization analysis.

---

<div class="post-metadata">

**Author:** ![ffetc](https://avatars.discourse-cdn.com/v4/letter/f/5e9695/32.png) [@ffetc](https://forums.swift.org/u/ffetc)\
**Post date:** [January 5, 2024, 3:33am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/5 "2024-01-05T03:33:16Z")

</div>

After trying a few of these, I settled on putting the loop inside a closure and assigning `bang` to the output - i.e.

```swift
struct Bing {
    let bang: String

    init() {
        bang = {
            while true {
                // do something iterative

                if /* some condition */ {
                    return "bong"
                }
            }
        }()
    }
}

```

> [@tera](#):
>
> i.e. refactor the while loop into a (local) function. This one won't work in "init" though.

I'll have a look later to see if and why a normal local function wouldn't work, because a closure seems to!

---

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [January 5, 2024, 5:45am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/6 "2024-01-05T05:45:42Z")

</div>

You can use [statement labels](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow#Labeled-Statements) to work around this:

```swift
struct Bing {
    let bang: String

    init() {
        loop: do {
            // do something iterative

            if /* some condition */ {
                bang = "bong"
                break loop
            }
            continue loop
        }

    }
}

```

---

<div class="post-metadata">

**Author:** ![ffetc](https://avatars.discourse-cdn.com/v4/letter/f/5e9695/32.png) [@ffetc](https://forums.swift.org/u/ffetc)\
**Post date:** [January 5, 2024, 6:01am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/7 "2024-01-05T06:01:08Z")

</div>

Ooh, I like this!

Or even inverted:

```swift
guard /* some condition */ else {
    continue loop
}

bang = "bong"

```

makes it very clear what's going on.

---

<div class="post-metadata">

**Author:** ![rayx](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rayx/32/12204_2.png) [@rayx](https://forums.swift.org/u/rayx)\
**Post date:** [January 5, 2024, 9:19am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/8 "2024-01-05T09:19:18Z")

</div>

I find having a possibly infinite loop in `init()` feels too hacky. So how about moving it outside `init()`? This version not only compiles without the tricks in above posts but also is easier to understand.

```swift
struct Bing {
    let bang: String

    init(bang: String) {
        self.bang = bang
    }

    static func create() -> Self {
        while true {
            if Bool.random() == true {
                return Bing(bang: "hello, word")
            }
        }
    }
}

```

P.S. If I understand Joe's comments correctly, it's a bug that your original version didn't work. My version and your closure version avoid that bug.

---

<div class="post-metadata">

**Author:** ![ffetc](https://avatars.discourse-cdn.com/v4/letter/f/5e9695/32.png) [@ffetc](https://forums.swift.org/u/ffetc)\
**Post date:** [January 5, 2024, 9:39am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/9 "2024-01-05T09:39:33Z")

</div>

> [@rayx](#):
>
> I find having a possibly infinite loop in `init()` feels too hacky.

Fair enough. This was a minimal, simplified example; in the actual code I was working on, the loop is pretty clearly terminating. And if you're implementing certain protocols (e.g. `Decodable`), you don't have any choice but to put things in `init`.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 5, 2024, 9:58am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/10 "2024-01-05T09:58:16Z")

</div>

> [@ffetc](#):
>
> I'll have a look later to see if and why a normal local function wouldn't work, because a closure seems to!

Closures and local functions should work so long as they don't use (capture) self. Instance member functions (methods) won't work as they are considered capturing self implicitly. If you are not using self one way or another – you may as well use a static method in your init.

---

<div class="post-metadata">

**Author:** ![rayx](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rayx/32/12204_2.png) [@rayx](https://forums.swift.org/u/rayx)\
**Post date:** [January 5, 2024, 10:17am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/11 "2024-01-05T10:17:51Z")

</div>

> [@tera](#):
>
> Closures and local functions should work so long as they don't use (capture) self. Instance member functions (methods) won't work as they are considered capturing self implicitly. If you are not using self one way or another – you may as well use a static method in your init.

A quick question: why does capturing self make a difference?

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 5, 2024, 11:56am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/12 "2024-01-05T11:56:35Z")

</div>

> [@rayx](#):
>
> A quick question: why does capturing self make a difference?

Before all stored properties are initialised self can't be used because otherwise you'd be able accessing its not yet initialised properties (either on the spot or by calling something that will do) which would be totally unsafe. Sometimes this rule is overly conservative and deems a bit too strict, e.g.:

```swift
class C {
    let x: Int
    init() {
        print(ObjectIdentifier(self)) // 🛑 can't do this yet, even if ObjectIdentifier won't need "x"
        x = 1
        print(ObjectIdentifier(self)) // ✅ ok
    }
}

```

but in the vast majority of cases this rule makes total sense.

---

<div class="post-metadata">

**Author:** ![Erik\_Eckstein](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erik_eckstein/32/320_2.png) [@Erik\_Eckstein](https://forums.swift.org/u/Erik_Eckstein)\
**Post date:** [January 9, 2024, 3:02pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/13 "2024-01-09T15:02:08Z")

</div>

> [@Joe\_Groff](#):
>
> `while true` is already special cased to be known as an infinite loop for unreachable code analysis, so I'd call it a bug that we don't handle it as such for definite initialization analysis.

Yes, it's a bug.  
Should be fixed here: [Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass by eeckstein · Pull Request #70787 · apple/swift · GitHub](https://github.com/apple/swift/pull/70787)

---

<div class="post-metadata">

**Author:** ![johnny1](https://avatars.discourse-cdn.com/v4/letter/j/3ec8ea/32.png) [@johnny1](https://forums.swift.org/u/johnny1)\
**Post date:** [January 9, 2024, 5:23pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/14 "2024-01-09T17:23:50Z")

</div>

I wouldn’t recommend using an implicitly unwrapped optional in this case, in fact I tend to avoid them in general because of the reduction in safety.

I also think using `while true` probably isn’t the best way to do this. You want to loop until some condition is met, so I would use that condition in the while loop.

```swift
// initialize any loop variables
while ! /* some condition */ {
    // the iterative stuff
}
self.bang = /* some value */

```

Of course this code is slightly different than yours since the condition is also checked before the first iteration happens, but it can probably be adjusted to the specifics of the situation.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 9, 2024, 7:58pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/15 "2024-01-09T19:58:24Z")

</div>

> [@johnny1](#):
>
> I wouldn’t recommend using an implicitly unwrapped optional in this case, in fact I tend to avoid them in general because of the reduction in safety.

Implicitly unwrapped optionals are not ["unsafe"](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/memorysafety/). It is "safer" to have the app trap (and terminate) because you forgot to initialise the variable properly, than to continue with some default value in the not-properly-initialised variable as if nothing bad happened.

I'd like to see what do they use in Rust/Haskell/etc in this situation.

---

<div class="post-metadata">

**Author:** ![johnny1](https://avatars.discourse-cdn.com/v4/letter/j/3ec8ea/32.png) [@johnny1](https://forums.swift.org/u/johnny1)\
**Post date:** [January 9, 2024, 8:06pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/16 "2024-01-09T20:06:58Z")

</div>

You’re right, I meant it in the sense of safe from my future self introducing a bug. Losing the guaranteed initialization and the assurance that it can’t be directly assigned a new value makes it less safe in that sense because it doesn’t have compiler guarantees about “proper” usage.

---

<div class="post-metadata">

**Author:** ![wadetregaskis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wadetregaskis/32/8494_2.png) [@wadetregaskis](https://forums.swift.org/u/wadetregaskis)\
**Post date:** [January 9, 2024, 10:30pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/17 "2024-01-09T22:30:28Z")

</div>

> [@tera](#):
>
> Implicitly unwrapped optionals are not ["unsafe"](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/memorysafety/).

For a _very_ specific and limited definition of 'safe'.

I think @johnny1 is wise to be hesitant to use implicitly unwrapped optionals, because "but it's fine, the app just crashed" is absolutely not a consoling response to any of the app's users. 🙂

He did say _reduction_ in safety, which I think is an accurate characterisation in lay terms. Not having the ability to crash - because the compiler ensures the pointer _cannot_ ever be invalid - is definitely _safer_, even by Swift's overload of the word.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 9, 2024, 10:52pm UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/18 "2024-01-09T22:52:26Z")

</div>

> [@wadetregaskis](#):
>
> He did say _reduction_ in safety, which I think is an accurate characterisation in lay terms.

Which I believe is not what happens with IUO's. The idea is that the app crashing will be picked up and fixed early during the app lifecycle, while the bug of not properly initialised variable could get unnoticed for a considerable amount of time. That's why our array's access could crash the app on out of bounds errors, when "messaging nil" we are not getting 0 magically, and so on and so forth. Would you prefer a banking app that transfers an incorrect amount instead of crashing?

---

<div class="post-metadata">

**Author:** ![Nobody1707](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nobody1707/32/2169_2.png) [@Nobody1707](https://forums.swift.org/u/Nobody1707)\
**Post date:** [January 10, 2024, 1:46am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/19 "2024-01-10T01:46:45Z")

</div>

Your right that they're technically safe, since they crash if you try and read them before initializing, but Implicitly Unwrapped Optionals are never needed in todays Swift. Definite initalization, lazy vars, and pooperty wrappers cover every concievable use of them. IUOs were only added to support `@IBOutlets` before we got property wrappers. They are legacy cruft only. Please do not use them in new code.

As to the main topic, the original code works fine once you use the other kind of while loop:

```swift
struct Bing {
    let bang: String
    init() {
        repeat {
             // the iterative stuff
        } while ! /* some condition */
        bang = "bong"
    }
}

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [January 10, 2024, 2:45am UTC](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280/20 "2024-01-10T02:45:39Z")

</div>

> [@Nobody1707](#):
>
> Implicitly Unwrapped Optionals are never needed in todays Swift... They are legacy cruft only. Please do not use them in new code.

I do not see this kind of language in the Swift book (and if what you said was true I'd expect to see a relevant wording in there). This is what it has to say about IUO's:

> [@](#):
>
> However, there’s a third scenario, in which _both_ properties should always have a value, and neither property should ever be `nil` once initialization is complete. In this scenario, it’s useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class. ...

See the full Country / Capital example [in there](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/automaticreferencecounting/#Unowned-References-and-Implicitly-Unwrapped-Optional-Properties). If Country and Capital are classes, every country must have a capital and every capital belongs to the relevant country and you don't want the unnecessary unwrap noise in the rest of the code there's no other option than using IUO's.

* * *

As far as original question goes I believe the best workaround would be to use a static method:

```swift
struct Bing {
    let bang: String

    init(param: Int) {
        bang = Self.staticMethod(param: param)
    }
    
    static func staticMethod(param: Int) -> String {
        while true {
            if /* some condtion */ {
                return someValue
            }
            ...
        }
    }
}

```

[Next page](https://forums.swift.org/t/recommended-way-to-initialise-a-mandatory-property-in-a-loop/69280.md?page=2)
