Today, a small problem, want to make a small project, in a controller to declare an array to store the content read from the database, declared as var bugcgs:[bugcategory], in fact, the corresponding form is var Classname:[classtype], unfortunately, this writing will be an error, such as:
I naturally know that variables in Swift must have an initial value (not necessarily, for example, in a function ). Xcode tip Do you want to add a required initializer ' init (coder:) '? Because I have a certain understanding of the optional type, I change it to var classname:[classtype]! or var classname:[classtype]? OK, now it's not an error. But this undoubtedly buried the potential danger, because the first run time database has no content, so want to insert some test data in, I do:
Yes, there are no errors, which also results in the last run-time error. Please look at the error:
Answer:
workaround: Declaring an array should be declared as an empty array var bugcgs:[bugcategory] = [Bugcategory] () . The cause of the error is also given, because when you declare an array of optional types, it is a nil. Look at the picture:
You can see the implicit declaration that it's a nil. So how do you call the Append method for a nil variable? At least that's what I understand now. If an empty array is declared (it is an instance, only there are 0 elements in it). As for the individual onepeople Although also nil, but below we use an instantiation method, then onepeople is no longer nil, but an example. Finally leave a question, why use array subscript method also will error, for example:
var peoples:[people]!//以下是错误做法!!peoples[0] = people()peoples[1] = people()
Q2: Unpacking error on array fatal Error:can ' t unwrap Optional