Thomas Quack
Thomas Quack

Reputation: 29

fatal error: unexpectedly found nil while unwrapping an Optional value - using UITableView

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.

Upvotes: 2

Views: 215

Answers (1)

Duncan C
Duncan C

Reputation: 131418

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.

Upvotes: 1

Related Questions