0

I have a struct, and have created a button in which I want to write something and then append the writing to my struct. I'm having trouble with how to write a correct code so that I append correctly the text from the button into my struct.

here is my struct:

 struct Candy{
  let category : String
  let name : String
}

 candies = [
  Candy(category:"test", name:"test 2"),
  Candy(category:"test", name:"test 4"),
  Candy(category:"test", name:"test 1"),
  Candy(category:"Music", name:"J-cole"),
  Candy(category:"Music", name:"Jay-z"),
  Candy(category:"Music", name:"Coldplay"),
  Candy(category:"Other", name:"Sophie"),
  Candy(category:"Other", name:"Frederic"),
  Candy(category:"Other", name:"test")]

    }

And this is the code for my button:

   @IBAction func addBar(sender: AnyObject) {

    let alert = UIAlertController(title: "New name",
                                  message: "Write name",
                                  preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Save",
                                   style: .Default,
                                   handler: { (action:UIAlertAction) -> Void in

                                    let textField = alert.textFields!.first

                                    self.candies.append(textField!.text!) // I have troubles with this line... not sure how to make this line correct..


                                    self.tableView.reloadData()
Frederic
  • 497
  • 2
  • 9
  • 22
  • That's not a struct, it's an `Array` of `Candy` Structs, written as: `Array`, or `[Candy]` for short. – Alexander Jul 11 '16 at 16:51
  • 1
    Side note: `category` would probably be better off as an `enum`. See the language guide section on `enum`. – Alexander Jul 11 '16 at 16:52

2 Answers2

0

Your problem line is trying to add a simple string to the array where is should create a new instance of your struct and add that. It isn't clear exactly how that should work as you have 1 string and the struct takes 2, but it's something like:

self.candies.append(Candy(category: "xxx", name: textField!.text!))
Wain
  • 118,658
  • 15
  • 128
  • 151
0

You have to create an instance of the struct Candy in order to add it to the array candies of type Candy, like in this way:

self.candies.append(Candy(category:"NameYouWant", name: textField!.text!))

In the above I suppose you want to the save the textField!.text! as the name property in the Candy, but you can change it as you want.

I hope this help you

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • I now I get a new error: This class is not key value coding-compliant for the key addBar.' – Frederic Jul 11 '16 at 17:07
  • 1
    You've experimenting another error very different from the issue you asked, see this answer http://stackoverflow.com/questions/3088059/what-does-this-mean-nsunknownkeyexception-reasonthis-class-is-not-key-valu – Victor Sigler Jul 11 '16 at 17:10