I have a JSON file from which I two icon names: normal
and active
.
I use them to get the system icons, which I'd like to put inside an image array.
When I load them separately it works just fine:
struct loadData: Hashable, Codable {
//load some data...
private var normal_name: String
private var active_name: String
var normal_icon: Image {
Image(systemName: normal_name)
}
var active_icon: Image {
Image(systemName: normal_name)
}
}
When I try to put the acquired images inside an array, it throws an error:
var icon: [Image] = [
normal_icon,
active_icon
]
Even if I try to load them directly, it still throws the same error:
var icon: [Image] = [
Image(systemName: normal_name),
Image(systemName: normal_name)
]
The error I get is this:
Cannot use instance member 'normal_icon' within property initializer; property initializers run before 'self' is available
I know I can use a computed property to fix this issue, my question is:
Why am I allowed to initialize the string (normal_name
) and then initialize the image (normal_icon
) without getting an error, but when I do it inside the array it doesn't work?
CodePudding user response:
You don't show us the context where the code:
var icon: [Image] = [
normal_icon,
active_icon
]
lives, but are you doing this:
struct loadData: Hashable, Codable {
//load some data...
private var normal_name: String
private var active_name: String
var icon: [Image] = [
normal_icon,
active_icon
]
}
If so, then you have to realize that normal_icon
in the array declaration is really a reference to self.normal_icon
so it is referencing self
while trying to set up the field icon
. But the fields of the object are initialized before self
is available so you
Cannot use instance member 'normal_icon' within property initializer; property initializers run before 'self' is available