I am confusing when declare the variable
the first one:
import Foundation
class ContentModel: ObservableObject {
@Published var modules:[Module]
init(){
getLocalData()
}
func getLocalData() {
}
}
→ This one return error: ‘self’ used in method call ‘getLocalData’ before all stored properties are initialized
Then I changed to this:
import Foundation
class ContentModel: ObservableObject {
@Published var modules=[Module]()
init(){
getLocalData()
}
func getLocalData() {
}
}
→ then the error dispeared
Anyone can explain when to decrale
var modules:[Module]
and when to use
var modules=[Module]()
In this particular case the declaration:
@Published var modules = [Module]()
says that modules
is to be an array of type Module
. The opening and closing parenthesis ()
on the end means to initialise the array.
It can be declared as above, or like this:
@Published var modules: [Module] = []
In both cases the array is created (initialised) but contains nothing.
1 Like
thanks for your kindly support. From your explaination, both cases are same, but I dont understant why only the fírst case throws error
When do we declare
var modules:[Module]
instead of
var modeule:[Module] = []
This form of declaration
@Published var modules:[Module]
does not include any initialisation. That’s why you got the error message
1 Like
That so kind of you Chris
That and initialization means to set a value
This is saying “hey modules you’re an array of type Module
” and that’s it, it has NO value, it just knows the type that it will be
Vs @Published var modules = [Module]()
Says “yo modules, you are an array of Module
objects, and are an empty array.
1 Like