Search code examples
arraysswiftuitableviewswift5

join two string - Swift


i have an application for my shop and in the cart viewController i have a tableView cell showing the user what they add to the cart and i want to join the number of items with the name, i tried this code and it works 100% but instead of showing it like this --> item1 (3 piece), item2 (4 piece), item3 (9 piece) .. it is show it like that item1,item2,item3 (349)

this is my code for the tableViewController

import UIKit


class cartTableViewController: UITableViewController {



@IBOutlet var priceLabel: UILabel!
@IBOutlet var totalOrder: UILabel!
@IBOutlet var cartTableView: UITableView!

override func viewDidLoad() {
    
    super.viewDidLoad()
    
    
  
}

// MARK: - Table view data source
override func viewWillAppear(_ animated: Bool) {
    
    priceLabel.text = "\(userData.selectedItemsPrice())"

   totalOrder.text =  "\(userData.allItemsToString()) (\(userData.allItemsToAmount())" // this is the line i use it  

 
    
    super.viewWillAppear(animated)
}
}

struct code:

import UIKit

struct userData {
static var selectedItem: Item? = nil
static var selectedItems: [Item] = []


static func allItemsToAmount() -> String {
    var allAmount: [String] = []
    for item in selectedItems {
        allAmount.append(item.amount)
    }
    return allAmount.joined(separator: "")
}

static func selectedItemsPrice() -> Double {
    var result: Double = 0
       for item in selectedItems {
        result = result + item.price
       }
       return result

}


static func storeName() -> String {
    var Store: [String] = []
    for item in selectedItems {
        Store.append(item.Store)
    }
    
    return Store.joined()
    
    
}


static func allItemsToString() -> String {
    var allNames: [String] = []
    for item in selectedItems {
        allNames.append(item.name)
    }
    
    return allNames.joined(separator: ","  )

    
}


}

struct Item: Equatable {
/// All of the animals
static let items : [Item] = {
    let bear: Item = .init(image: UIImage(named: "bear"), name: "bear", price: 1, amount: "", Store: "")
    return [bear]
    
 
 
}()

var image: UIImage?
var name: String
var price: Double
var amount: String
var Store: String
}

Solution

  • This can be simply solved as

    totalOrder.text = selectedItems.map { "\($0.name) (\($0.amount) piece)" }.joined(separator: ", ")