0

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
    }

1
  • Any particular reason you're not using Firestore over RTDB? Commented Mar 31, 2019 at 23:12

1 Answer 1

1

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()
        })


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.