What is the best way or elegant way to get all elements whithout spaces and ignore "DOMICILIO" and the next elements for example : "LOAIZA" "HERRERA" "JESUS" (This is my expected output)
In this case I have one string with 2 elements ("LOAIZA\nHERRERA")
["LOAIZA HERRERA", "JESUS", "DOMICILIO", "CALLE1", "CALLE2"]
var dataID = ["LOAIZA HERRERA", "JESUS", "DOMICILIO"]
for i in dataID {
if i.contains(" "){
print(i) // LOAIZA HERRERA
let dataSeparate = i.components(separatedBy: " ")
print(dataSeparate) // ["LOAIZA", "HERRERA"]
}
}
CodePudding user response:
Separate the terms by " "
and flatMap
into a new array. Then, find the index of "DOMICILIO" if it exists and use the segment of the array up to that point.
func findResult(dataID: [String]) -> Array<String> {
let terms = dataID.flatMap { $0.components(separatedBy: " ")}
let indexOfDom = terms.firstIndex(of: "DOMICILIO")
if let indexOfDom = indexOfDom, indexOfDom > 0 {
return Array(terms[0...(indexOfDom - 1)])
} else {
return terms
}
}