2

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.

9
  • try to print players!.count I guess it's returning nil Commented Jul 22, 2015 at 0:52
  • @Aladin - Yes it does. What should i do? The error appear when I try to open the view controller that contains the UITableView. Commented Jul 22, 2015 at 0:52
  • can you share the declaration of players Commented Jul 22, 2015 at 0:55
  • @Aladin - var players = NSUserDefaults().arrayForKey("playersKey") Commented Jul 22, 2015 at 0:56
  • 2
    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/zGT8AqjE Commented Jul 22, 2015 at 2:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, worked! Can you also check my new question on top?
Don't edit your original question to ask a new question. Ask a new question! This site is used by lots of people who find answers to past questions helpful. By editing your original question you destroy that history. Also, if my answer meets your needs, accept it. (Click the checkmark.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.