swiftstringxcodestruct

Convert struct to [string]


I created a struct and want to convert to [[String]]

 var ucetPlatby = [struct_ucetPlatby]()

     struct struct_ucetPlatby {
            let id: Int
            let trasaid: Int
            let cena: Decimal
         
            }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        ucetPlatby.append(.init(id: 1, trasaid: 1, cena: 33))
        ucetPlatby.append(.init(id: 3, trasaid: 1, cena: 44))
        ucetPlatby.append(.init(id: 4, trasaid: 1, cena: 55))
        
        print(ucetPlatby)

        }

...which results in:

[UD.ViewController.struct_ucetPlatby(id: 1, trasaid: 1, cena: 33), UD.ViewController.struct_ucetPlatby(id: 3, trasaid: 1, cena: 44), UD.ViewController.struct_ucetPlatby(id: 4, trasaid: 1, cena: 55)]

But how can I convert the struct object to something like [String]

[["1", "1", "33"], [["3", "1", "44"], [["4", "1", "55"]]

Solution

  • It depends on how you want to format the numbers, but if you want the simplest approach, you would just use the default with "\(...)":

    let stringVersion = ucetPlatby.map { ["\($0.id)", "\($0.trasaid)", "\($0.cena)"]}
    

    The type of this is [[String]], which seems to be what you mean. The final output would be:

    [["1", "1", "33"], ["3", "1", "44"], ["4", "1", "55"]]
    

    (I believe your output is not quite what you meant; the brackets don't balance.)