Q2: Unpacking error on array fatal Error:can ' t unwrap Optional

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.