2

I have two string var strDate = "2019-10-14, 2019-07-30" and var strID = "162670, 127097", i wan to create class modal from above two string and append to ModalData like :

class ModalData{
    var id:String
    var booking_date:String

    init(id:String,booking_date:String) {

        self.id = id
        self.booking_date = booking_date
    }
}

and show modal to class to UITableView in Swift.

Dilip Tiwari
  • 1,441
  • 18
  • 31

1 Answers1

2

This should work:

class ModalData
{
    var id:           String
    var booking_date: String

    init(id: String, booking_date: String)
    {
        self.id           = id
        self.booking_date = booking_date
    }
}

var strDate = "2019-10-14, 2019-07-30"
var strID   = "162670, 127097"

let dateArray = strDate.split(",").map { $0.trimmingCharacters(in: .whitespaces) }
let idArray   = strID.split(",").map { $0.trimmingCharacters(in: .whitespaces) }

var modalDataArray = [ModalData]()
for i in 0..<max(dateArray.count, idArray.count)
{
    modalDataArray.append(ModalData(id: idArray[i], booking_date: dateArray[i]))
    print(modalDataArray.last!)
}

What this does is:

  • Turn the string of dates into an array of dates (dateArray).
  • Turn the string of ids into an array of ids (idArray).

(Both splitting by , and removing whiteSpaces around the string)

Then check the max amount in both arrays, just to be safe. Using this, we can loop through the array and create ModalData objects.

Jeroen
  • 2,011
  • 2
  • 26
  • 50
  • This can probably be optimized (written in nicer/shorter way). But it does the job. – Jeroen Dec 18 '19 at 08:42
  • What do you mean with 'print together'? Also, `print(modalDataArray)` definitely won't print `[CheckTableViewBack.OPDModalPrevious,...]`. – Jeroen Dec 18 '19 at 08:52
  • what version of swift are you using? – L33MUR Dec 18 '19 at 08:58
  • If you're using my code, you can just do `print(modalDataArray)`. You're probably just doing something else, since `[CheckTableViewBack.OPDModalPrevious,...]` is printed. – Jeroen Dec 18 '19 at 09:01
  • You can also print it inside the `for`-loop. I added this to the code. Or you can do `modalDataArray.forEach { print("id: \($0.id), booking_date: \($0.booking_date)") }`. – Jeroen Dec 18 '19 at 09:04
  • 2
    thanks its working bro and also i m giving upvote to you if any question or issue i will mention here@JeroenJK – Dilip Tiwari Dec 18 '19 at 09:06
  • Good, no problem :-) And yes, let me know any problem you have! – Jeroen Dec 18 '19 at 09:06