MarksCode MarksCode - 27 days ago 6
Swift Question

Struct found nil while unwrapping

I have a struct named

AwardData
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

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"