0

I have an array like this:

var converter1 = [
        ["title": "value1", "kf": "1"],
        ["title": "value2", "kf": "4.324"]]

And if, else case in cellForRowAt:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! resultTableViewCell


            cell1.nameResult.text = converter1[indexPath.row]
            cell1.labelResult.text = converter1[indexPath.row]


            return cell1

How could I in nameResult.text show "title" and "kf" in labelResult?

3
  • Do you want to display the keys ("title" and "kf") or the values ("value1" and "1")? Commented Feb 5, 2018 at 18:10
  • @vadian “title” and “kf” - type names. I want to show it’s values like “value1” is “1” Commented Feb 5, 2018 at 18:12
  • cell1.nameResult.text = converter1[indexPath.row]["title"] Commented Feb 5, 2018 at 18:12

3 Answers 3

2

You have an array of dictionaries. Each dictionary seems to contain a "title" key/value pair and a "kf" key/value pair. I'm not completely clear on what you want to do, but you might try something like this:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! resultTableViewCell

cell1.nameResult.text = converter1[indexPath.row]["title"]
cell1.labelResult.text = converter1[indexPath.row]["kf"]

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

1 Comment

Take a look at vadian's suggestion of creating a struct to model your data. That's a better way to go than using a dictionary.
2

Just get the values with key subscription

let item = converter1[indexPath.row]
cell1.nameResult.text = item["title"]
cell1.labelResult.text = item["kf"]

A much better solution is a custom struct

struct Converter {
   let title, kf : String 
}

let converter1 = [
    Converter(title: "value1", kf: "1"),
    Converter(title: "value2", kf: "4.324")]

...

let item = converter1[indexPath.row]
cell1.nameResult.text = item.title
cell1.labelResult.text = item.kf

2 Comments

Beat you to it, by at least 10 seconds! 😝
I like your edit to suggest a custom struct. (voted.) That's much safer and clearer than a generic dictionary. And if the source data is JSON, it's trivial to use the new JSONDecoder to create a custom struct directly from the JSON.
0

I good way to deal with this kind of problem is to use a playground and let type inference tell you what data types you're dealing with. Here's an example of taking your structure apart.

let converter1 = [
    ["title": "value1", "kf": "1"],
    ["title": "value2", "kf": "4.324"]]
let val0 = converter1[0]
if let strTitle = val0["title"],
    let strKf = val0["kf"] {
    print("\(strTitle) : \(strKf)")
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.