user10590916
user10590916

Reputation:

Loading array data into a tableview

I have a firebase database setup that I have returning a few keys that I want. I want those keys to be the title of a tableview row. When I run the following code, it returns exactly what I want in an Array(in this example, [Athens, Delaware]). I load this array from the view did load method.

How can I get each item in the array to be a cell row in my tableView?

When I attempt to execute the following code, i get this error in return:

Could not cast value of type 'Swift.Array' (0x10c7ed2c0) to 'Swift.String' (0x10c7d2888).

let ref = Database.database().reference()

    var markets: [loadMyData] = []

    var myKey = [Any]()

    override func viewDidLoad() {
        super.viewDidLoad()



        ref.child("Markets").observeSingleEvent(of: .value, with: { (snapshot) in

            var myNewKey: [Any] = []

            let allMarkets = (snapshot.value as! NSMutableDictionary).allKeys
            myNewKey.append(allMarkets)
            self.myKey = myNewKey
            self.tableView.reloadData()
        })


    }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return myKey.count

    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let allMarkets = myKey[indexPath.row]

        cell.textLabel?.text = allMarkets as! String
        return cell
    }

Upvotes: 0

Views: 72

Answers (1)

Sina KH
Sina KH

Reputation: 565

This error happens because the code (snapshot.value as! NSMutableDictionary).allKeys returns an array and you are adding this array as an array item to myKey! And of course, You can not cast an array to a String.

Try this code and see what happens:

let ref = Database.database().reference()

    var markets: [loadMyData] = []

    var myKey = [Any]()

    override func viewDidLoad() {
        super.viewDidLoad()



        ref.child("Markets").observeSingleEvent(of: .value, with: { (snapshot) in

            var myNewKey: [Any] = []

            let allMarkets = (snapshot.value as! NSMutableDictionary).allKeys
            self.myKey = allMarkets
            self.tableView.reloadData()
        })


    }

Upvotes: 1

Related Questions