ardakaraca ardakaraca - 1 year ago 65
Swift Question

How to split array objects into two(or 2d array) by seperation character

I want to split an array like shown below.

let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]


let firstArray = ["Europe", "Europe", "America", "America"]
let secondArray = ["France", "Italy", "USA", "Canada"]
let thirdArray = ["Paris", "Rome", "Washington", "Ottawa"]

By separating into these three arrays I want to split the data income and present it in a

Answer Source

Not the best solution, but with the expected result (hints are in the code comments):

let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]
var firstArray = [String]()
var secondArray = [String]()
var thirdArray = [String]()

for element in arrayToSplit {

    // new array with substrings divided by "|#|" e.g. ["Europe", "Europe", "America", "America"]
    let newArray = element.componentsSeparatedByString("|#|")

print("first array: \(firstArray)") // first array: ["Europe", "Europe", "America", "America"]
print("second array: \(secondArray)") // second array: ["France", "Italy", "USA", "Canada"]
print("third array: \(thirdArray)") // third array: ["Paris", "Rome", "Washington", "Ottawa"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download