Initializer is not appending data

I am trying to append whatever is in both textfields to the MyData set. However the data is not be appended into MyData.

   let sortedArray =   MyData.init(company: textA.text!, scorej: Int(textB.text!)!) is being unused.

How can I append this data?

 import UIKit

struct MyData {
var company = String()
var scorej: Int

var data = [
MyData(company: "smiths", scorej: 4),
MyData(company: "lukes", scorej: 4),

   let sortedArray = data.sorted(by: { ($, $1.scorej) < ($, $0.scorej) })

  class ViewController: UIViewController {

    @IBOutlet var textB: UITextField!
    @IBOutlet var textA: UITextField!

   @IBAction func store(_ sender: Any) {
  MyData.init(company: textA.text!, scorej: Int(textB.text!)!)

Your store function calls the MyData initialisation function, which creates a MyData instance, but doesn’t add it to the data property or the sortedArray constant, so neither of them will change.


    let newData = MyData(company: textA.text!, scores: Int(textB.text!)!)

You may have to either recalculate your sorted array at this point, or declare it as a computed property so it gets recalculated whenever it’s requested.

This works but when it is printed I can only see the 3rd entry. If i add 5 entries of different names and scores I can only see the first 3. How can I make it so I can see all the entries of data.

Without seeing the code, I couldn’t tell you why it’s not doing what you expect.

At the moment I’d expect that when the store function gets called you’re creating an entry, adding it to the array, resorting the array, and printing all of it. So, for example, make sure you’re not replacing the array or any values in it.

This topic was automatically closed after 166 days. New replies are no longer allowed.