Как отобразить словарь строк и парных символов в табличном представлении - PullRequest
0 голосов
/ 23 октября 2018

Я пытаюсь отобразить словарь [String: [Double]] в UITableView, но я получаю неожиданное поведение, когда удваивается появляется с различными форматами от оригинала.Вот мой основной код:

    var resdict = ["Joao":[55.5,43.8,88.5],"Carlos":[65.5,45.8,58.5],"Eduardo":[45.5,75.8,53.5]]

struct Objects {
    var sectionName : String
    var sectionObjects : [Double]
}
var objectArray = [Objects]()


    //table
@IBOutlet weak var resultsTable: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objectArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as UITableViewCell
    let name = objectArray[indexPath.row].sectionName
    let notas = objectArray[indexPath.row].sectionObjects

    cell.textLabel?.text = "\(indexPath.row + 1) \(name) -> \(notas)"

    return cell
} 

И при viewDidLoad:

           for (key, value) in resdict {
        print("\(key) -> \(value)")
        objectArray.append(Objects(sectionName: key, sectionObjects: value))
    }

Результаты:

1 Eduardo -> [45.5, 75.799999999999997, 53.5]

2 Joao -> [55.5, 43.799999999999997, 88.5]

3 Carlos -> [65.5, 45.799999999999997, 58.5]

Я знаю, что мне следует применить что-то вроде String (формат: "% .2f", ...) но где и как?

Ответы [ 3 ]

0 голосов
/ 23 октября 2018

1 вам нужно передать данные в массив объектов, 2 использовать раздел, чтобы установить заголовки и строку для оценок

 override func viewDidLoad() {
            super.viewDidLoad()
            self.tableView.dataSource = self
            resdict.forEach({(k,v) in
                objectArray.append(Objects(sectionName: k, sectionObjects: v))
            })
            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
            self.tableView.reloadData()
        }

        var resdict = ["Joao":[55.5,43.8,88.5],"Carlos":[65.5,45.8,58.5],"Eduardo":[45.5,75.8,53.5]]

        struct Objects {
            var sectionName : String
            var sectionObjects : [Double]
        }
        var objectArray = [Objects]()


        //table
         func numberOfSections(in tableView: UITableView) -> Int {
            return objectArray.count
        }
         func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return objectArray[section].sectionObjects.count
        }
         func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            let name = objectArray[section].sectionName
            return name
        }

         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as UITableViewCell
            let notas = objectArray[indexPath.section].sectionObjects[indexPath.row]
            cell.textLabel?.text = "\(notas)"

            return cell
        }
0 голосов
/ 23 октября 2018

Как уже говорили другие, вы можете использовать map и join для преобразования массива значений типа double в строку, которая начинается с "[", имеет значения, разделенные запятыми, а затем заканчивается "]"

Однако проще было бы изменить вашу строку

let notas = objectArray[indexPath.row].sectionObjects

на

let notas = objectArray[indexPath.row]
  .sectionObjects
  .map { String(format: ,%.2f", $0) }

Это преобразовало бы ваш массив значений типа double в массив строк с двумя десятичными знаками.

Тогда выражение "(notas)` отобразит массив строк с открывающими и закрывающими скобками и с разделителями запятых.

0 голосов
/ 23 октября 2018

Простым решением является добавление вычисляемого свойства в Objects (на самом деле единственное Object), чтобы сопоставить массив Double с String и соединить его через запятую.

struct Objects {
    var sectionName : String
    var sectionObjects : [Double]

    var objectsStringRepresentation : String {
        return sectionObjects.map{String(format: "%.2f", $0)}.joined(separator:", ")
    }
}

...

let notas = objectArray[indexPath.row].objectsStringRepresentation 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...