Matthew Bradshaw Matthew Bradshaw - 2 years ago 68
Swift Question

Can't Unwrap An Optional When Populating Cell

I hate to post this because it seems like basic Swift, however, I cannot find a way to get this optional unwrapped and I have an idea that it may be with the way NSUserDefaults is storing it, but I'm not sure.

I am saving an [String] as so:

NSUserDefaults.standardUserDefaults().setObject(infectedNamesArray, forKey: "infectedNamesArray")

and recalling it like this:

if let infected = NSUserDefaults.standardUserDefaults().objectForKey("infectedNamesArray")
infectedNamesArray = infected as! [String]

I am using the array to populate a reusable cell like this:

switch whichScoreSet
case 0:
cell.nameLabel.text = "Test"
cell.scoreLabel.text = "Test"
case 1:
cell.nameLabel.text = infectedNamesArray[indexPath.row]
cell.scoreLabel.text = "\(infectedGameScoreTotals["\(infectedNamesArray[indexPath.row])"]!)"
case 2:
cell.nameLabel.text = "Test"
cell.scoreLabel.text = "Test"
print("Something Went Wrong")

Everything works fine, I am able to switch between table data and load views. When viewing the data from cell.nameLabel.text, it consistently displays optional. i.e. optional(valueFromArray)

I have tried to force unwrap it, and Xcode tells me I can't unwrap a string. I have tried casting it as a string and Xcode tells me it would make no difference because it is already a string.

I am at a loss on this basic Swift, so please forgive the question. Techniques from many other SO posts provide the same results.

What am I overlooking here?


The variable is declared outside of a class as such.

var infectedNamesArray = [String]()

Answer Source

infectedNamesArray[indexPath.row] is supposed to be safe so you can use it directly

let infectedName = infectedNamesArray[indexPath.row] 
cell.nameLabel.text = infectedName

the value for key infectedName in infectedGameScoreTotals can be missing and is optional, so try

let scoreTotal = infectedGameScoreTotals[infectedName]
cell.scoreLabel.text = scoreTotal != nil ? "\(scoreTotal!)" : "n/a"

n/a is a placeholder to be displayed in case the dictionary key is no available.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download