-2

I've been working on this for three nights and have pretty much lost my weekend, so I would appreciate your help.

I'm being told that I'm not instantiating - I'm not 100% sure of how that works, I have read online but would like to see an example that has to do with my particular code.

In the app delegate I have this:

var myDataSource: Array<Dictionary<String,Any>>!

Then, on my first screen I want to capture the username to myDataSource (my array of dictionary's). I attempted this with:

class UserInfoViewController: UIViewController {
    @IBOutlet weak var firstName: UITextField!
    var userName: String?

    @IBAction func submitName(_ sender: UITextField) {
        userName = firstName.text
        if userName != nil {
            let saveName: [String: Int] = ["userName!": 0]
            myDataSource.append(saveName)
            print(firstName)
        }
    }

I have knowledge about unwrapping variables, however I think this has to do with instantiation, please tell me if I'm wrong.

  • 1
    FYI - use simpler syntax: `var myDataSource: [[String:Any]]!` – rmaddy Mar 26 '17 at 22:16
  • I disagree with you Maddy, I don't see how the question you referenced answers my question about dictionary usage... I've seen things like what you referenced online but I am unable to connect what it means to the issue I'm having so I decided to ask a question with my specific variable and with my specific code example (using the app delegate). – Damon McCall Mar 26 '17 at 23:38
  • I think this link is closer to what I need but it doesn't work when I try to code for it... http://stackoverflow.com/questions/28410218/how-to-create-an-array-of-dictionaries – Damon McCall Mar 27 '17 at 02:56

1 Answers1

1

myDataSource is an optional. You never instantiate it, so it is of course nil, when you try to append something to it. You should instantiate it right away, or check for nil, before you add something to the array

Frederik
  • 384
  • 3
  • 7
  • Thanks for this answer Frederick, it's much more helpful than what rmaddy offered. I thought I had checked for nil with the if statement? Also, what do you mean about not instantiating it? – Damon McCall Mar 27 '17 at 01:46
  • The userName is not nil, it is the data source that is nil. You put a ! at the end of the declaration like this: `var myDataSource: Array>!` The ! means "Hey, there is going to be a value here, but not right now". If you replace the ! with (), the array will be instantiated right away as empty, and that will fix your problem – Frederik Mar 27 '17 at 08:00
  • You rock, thank you so much! – Damon McCall Mar 30 '17 at 02:58