Reputation: 81
I am working on a project where I found an array variable
var items: [[String: String]]!
I searched in google how to define an empty array, I got the result as
var itemsNew: [[String: String]]()
while using items array getting an error while appending data
self.appDelegate.items.append([Name: "sdsd",
rate: "0.2",
Quantity:"3",
Taxable:"true",
Category: "",
inven: "true",
amount : "0.23",
mod: "",
darray: "",
list: "",
famount: "0.0"])
giving an error "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file". I am giving hardcore value but still, it's crashing. Don't know why it's crashing. can somebody help me?
Upvotes: 0
Views: 865
Reputation: 141
[[String: String]]()
is an object of Array of type [[String: String]]
.
Where as [[String: String]]!
is an arrayType of type [[String: String]]
which can't be nil while executing because it is an implicitly unwrapped optional.
You are getting Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file
because items
was never initialised. But you are trying to add an item to items
which is actually a null value. You can solve this error by replacing items
declaration with the below code.
var items: [[String: String]] = [[String: String]]()
And the declaration of itemsNew is also wrong. You can declare it as below.
var itemsNew = [[String: String]]()
or
var itemsNew: [[String: String]] = [[String: String]]()
Upvotes: 1
Reputation: 16341
The first object items
is declared as an implicitly unwrapped optional. If you use it as items
without the ?
optionally unwrapping, you're saying that you know for sure that there is a value in items
I'm sure it's not nil
if it doesn't have a value I want the app to crash.
In the second case, you're creating a non-optional
empty array of dictionary itemsNew
which cannot be nil
but is empty at the time of declaration. In summary, you can replace the optional declaration to empty declaration they would still store the same type in these properties.
var items = [[String: String]]()
var itemsNew = [[String: String]]()
Upvotes: 1
Reputation: 675
Because
var items: [[String: String]]! not allocating memory or giving back, the reference to item where developer can append the items.
So var itemsNew: [[String: String]]()
is working as it is creating memory where you can append items.
Upvotes: 2