Swift -- how to init a member variable which is a class reference

Code Block
class A {
init(_ p: String) {...}
}
struct B {
var a : A
init(_ p: String) {
self.a = A(p)
}
}


This fails to compile because it claims that a is being used before being initialized. I can't do it in the var a : A declaration line because I need to use the initialization argument. I can't make a optional because its actually an ObservableObject and I need to use the self.$a.keypathhere syntax on it which clashes badly with it being optional (plus a isn't really optional, its just this annoying initialization problem).

How to solve this dilemma?

Why do you say it does not work ? Which Xcode version ?

I tested (both in playground and in an app) with Xcode 11.3:

Code Block
class A {
init(_ p: String) { print(p) }
}
struct B {
var a : A
init(_ p: String) {
self.a = A(p)
}
}
let b = B("Hello B")


when line 12 is executed, I get print in log
Hello B

as expected.

I also checked in Xcode 12beta3.
Works OK as well.

What is the code in the init you did not show but replaced by ellipsis ?
I tried your code exactly as is (*1) both in Xcode 11.6 and 12 beta 3.
(*1) I needed to replace ... to /*...*/, and that's all I touched.

And it compiles successfully without any problems.

I can't make a optional because its actually an ObservableObject and I need to use the self.$a.keypathhere syntax on it which clashes badly with it being optional (plus a isn't really optional, its just this annoying initialization problem).

Seems you have failed to create an issue reproducible example. Even if I add : ObservableObject to A and @ObservedObject to var a, no problem occurs.

How to solve this dilemma?

Obviously this does not cause dilemma. Please show the right code enough to reproduce your issue.
I'm on the latest beta (3), and it happens with earlier versions too. There are a few example on StackOverflow of people having the same issue. I worked around it by removing the code from my init of A, and calling it explicitly from the init of B (and other places that need to make an A). The issue is that I don't want that code to execute twice, but the compiler seems to want to force me to initialize it in the declaration in B (without access to the argument I need) and then again in the init of B. By making the init of A lightweight, I don't care anymore... but now need a secondary step to ensure it is properly initialized.


There are a few example on StackOverflow of people having the same issue. 

Please show the link.
We cannot replicate your problem, so please post the real code where you get the problem. It may be in part of code that you did not post.
Swift -- how to init a member variable which is a class reference
 
 
Q