MarksCode MarksCode - 1 year ago 62
Swift Question

Struct found nil while unwrapping

I have a struct named

with 3 fields, a
title : String
, a
description : String
, and
completed : Bool
. I'm trying to create an instance of one of these then set its data like this:

var data : AwardData!

switch awardNum
case 0:
data.title = "Roomie"

However I'm running into an error:
unexpectedly found nil while unwrapping an Optional value

Is how I'm making the instance of the struct incorrect?

jjs jjs
Answer Source

var data: AwardData! declares an optional variable. It's almost as if you wrote var data: AwardData?. The ! at the end makes it implicitly unwrapped, which basically just means that the compiler won't complain about you using it like a normal (non-optional) variable.

The real problem is that you haven't initialized your data variable yet. You only declared its type, but didn't create the actual structure. It's nil, but you try to assign a value to its title.

You could do this instead:

var data = AwardData()

And then set the title without problems:

data.title = "Roomie"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download