Search code examples
iosarraysswiftxcodecocoa-touch

How to Print Array in Label?


I'm trying to print my Array into my label but I don't found any way to do that.

Here is my array.

var lapTime: [[Double]] = [[]]

And there is where I put something of cool in my label

let str = NSString(format: "%.2f", rows[indexPath.row]["time"]! as! Double)
let arr = ??? // Here I Want to put my array
cell?.textLabel?.text = "\(indexPath.row + 1) -> \(str) -> \(arr)"

Thank you for your help !


Solution

  • I assumed your lapTime is like below,

     let lapTime: [[Double]] = [[33.34,22.876,34.0]]
    

    Method 1:

    let arr = lapTime[0].map { (double) -> String in
        return String(double)
    }.joined()
    
    self.label.text = arr
    

    or

    let arr = lapTime[0].map { (double) -> String in
                return String(double)
                }.joined(separator: ", ")
    
    self.label.text = arr
    

    Method 2:

    for time in lapTime[0]{
        let arr  = (self.label.text ?? "")+" "+String(time) //+"<space>"+ to +","+ if you need lap times are comma separated. 
        self.label.text = arr
    }
    

    Note:

    The lapTime == [[33.34,22.876,34.0],[33.34,22.876,34.0]]and you had a UITableView, then replace lapTime[0] to lapTime[indexPath.row].

    let me know is that you need.

    Output:

    enter image description here