2
votes

I am using UITableView inside a View Controller.

In viewDidLoad i have this:

var PlayersUserDefault = NSUserDefaults.standardUserDefaults()
        if (PlayersUserDefault.arrayForKey("playersKey") != nil){
            players = PlayersUserDefault.arrayForKey("playersKey")
        }

and this code gives me error:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return players!.count
}

fatal error: unexpectedly found nil while unwrapping an Optional value

I don´t understand this, can someone help me. Sorry, my English is not that good.

1
try to print players!.count I guess it's returning nilAlaeddine
@Aladin - Yes it does. What should i do? The error appear when I try to open the view controller that contains the UITableView.Thomas Quack
can you share the declaration of playersAlaeddine
@Aladin - var players = NSUserDefaults().arrayForKey("playersKey")Thomas Quack
I have restored the question to the original content. From now on, please ask new questions using the Ask Question button. I saved the contents of your new question here, so you can just copy and paste it when asking a new question: pastebin.com/zGT8AqjEAndy Ibanez

1 Answers

1
votes

The problem is that NSUserDefaults returns nil if the key does not contain a value. NSUserDefaults method like objectForKey and arrayForKey return optionals.

If the key doesn't exist, they return nil.

Try this instead:

func tableView(tableView: UITableView, 
  numberOfRowsInSection section: Int) -> Int 
{
    return players?.count ?? 0
}

That uses the "nil coalescing operator" which returns the value if it's not nil, or the value after the ?? if it is nil.