An error occurs when you try to substitute the structure properties with the value received by the init
argument.
In selected=state
on the second line of init
self'used before all stored properties are initialized
The error appears.
structure Icon:View {
varimageName: String=""
@Binding var selected:Bool
init(_image:String,_state:Bool){
imageName = image
selected = state
}
varbody:someView {
VStack {
if self.selected {
back_selected()
Image(imageName)
.frame (width:98, height:95)
.clipShape (Circle())
} else {
back_normal()
Image(imageName)
.frame (width:98, height:95)
.clipShape (Circle())
}
}
}
}
As indicated in Answer to another question, variable declarations with propertyWrapper attributes such as @Binding
appear to be normal variable declarations, but the compiler treats them as follows:
var_selected: Binding <Bool >
var selected:Bool {
get{
_selected.wrappedValue
}
set {
_selected.wrappedValue = newValue
}
}
(Same as @State
, $selected
is also declared computational properties, but @Binding
is not very useful and should be omitted.)
In other words, the Bool
type property selected
is a computational property that does not require initialization, and must be used after all other instance properties have been initialized, as well as the instance method.
On the other hand, _selected
that does not appear in the actual code is a retractable property that requires initialization, so you must initialize it before using selected
.
Therefore, if you define init
yourself, this is what it looks like.
init(_image:String,_state:Binding<Bool>){
imageName = image
_selected=state
}
In this case, the Also, The initializer for this signature is automatically generated, so you should use it.state
in the second argument means that Binding<Bool>
type, not Bool
type, so true
and false
type constants cannot initialize, but refers to the
type of
Icon
is a structure, so if you do not define init
yourself, init (imageName: String, selected: Binding <Bool >)
© 2024 OneMinuteCode. All rights reserved.