# SwiftUI @State PW exact same code different result if another optional is added!? :=(

**URL:** <https://forums.swift.org/t/swiftui-state-pw-exact-same-code-different-result-if-another-optional-is-added/62789>\
**Category:** Using Swift\
**Created:** [January 25, 2023, 6:58pm UTC](https://forums.swift.org/t/swiftui-state-pw-exact-same-code-different-result-if-another-optional-is-added/62789 "2023-01-25T18:58:18Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [January 26, 2023, 11:38pm UTC](https://forums.swift.org/t/swiftui-state-pw-exact-same-code-different-result-if-another-optional-is-added/62789/11 "2023-01-26T23:38:22Z")

</div>

How would you describe this bug? Is this a SwiftUI or Swift bug?

My minimum sample code demonstrating the problems:

```swift
import SwiftUI

// this is the baseline version and see how thing can change by simply re-arraging init order or initialization of `b`
struct ContentViewCase1: View {
    @State var a: Int?
    @State var b: Optional<Int> // ! b/c this is not initialized,
    
    
    init() {
        a = 1234
        b = 4444
    }
    
    var body: some View {
        VStack {
            Text("a = \(a.map({ $0.formatted() }) ?? "nil")")
            Text("b = \(b.map({ $0.formatted() }) ?? "nil")")
        }
    }
}

// the following two views should be the same as above but is not
// how do you describe this bug to apple for filing a feedback to SwiftUI
// or is this a Swift lang bug?

struct ContentViewCase2: View {
    @State var a: Int?
    @State var b: Optional<Int> // ! b/c this is not initialized,
    
    
    init() {
        b = 4444 // ! just reverse the order and we get another result
        a = 1234
    }
    
    var body: some View {
        VStack {
            Text("a = \(a.map({ $0.formatted() }) ?? "nil")")
            Text("b = \(b.map({ $0.formatted() }) ?? "nil")")
        }
    }
}

struct ContentViewCase3: View {
    @State var a: Int?
    @State var b: Optional<Int> = 9999 // by assigning something here
    
    
    init() {
        a = 1234 // a can no longer be initialized because due to b being init'ed, it get init'ed, unlike case 1
        b = 4444   
    }
    
    var body: some View {
        VStack {
            Text("a = \(a.map({ $0.formatted() }) ?? "nil")")
            Text("b = \(b.map({ $0.formatted() }) ?? "nil")")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentViewCase1()
        ContentViewCase2()
        ContentViewCase3()
    }
}

```

---

_[View the full topic](https://forums.swift.org/t/swiftui-state-pw-exact-same-code-different-result-if-another-optional-is-added/62789)._
