Reputation: 541
I've a data coming from api which is in the form
"A,B,C,D,E\n
17945,10091,10088,3907,10132\n
2,12,13,48,11"
in the above form.
The meaning of data is A is mapped to 17945 and 2 (A->17945->2) similarly for others. I want to save this data on my model array
struct DataModel {
var name : String
var id1 : String
var id2 : String
}
The question is how do I do this effectively.
What Im thinking is splitting the the data from api , creating arrays respectively and initialising the data model accordingly, but is there a another way to do this using dictionaries , it is not neccassary to use model here , I just need all the respective data in one go.
Upvotes: 0
Views: 83
Reputation: 2204
I don't know if it is what you need, but one of the variants how to
struct DataModel {
var name: String
var id1: String
var id2: String
public init(n: String, i1: String, i2: String) {
name = n
id1 = i1
id2 = i2
}
}
let numberOfArrays = string.components(separatedBy: "\n").count
let aString = string.replacingOccurrences(of: "\n", with: ",").components(separatedBy: ",")
let step = aString.count / numberOfArrays
for i in 0..<step {
allElements.append(DataModel(n: aString[i], i1: aString[i + step], i2: aString[i + step * 2]))
}
UPDATE:
here is else one more variant with dictionary result
private func parse() {
var dictionary: [Int: String] = [:]
_ = inputString
.components(separatedBy: "\n")
.compactMap { $0.components(separatedBy: ",") }
.compactMap { arr in
arr
.enumerated()
.compactMap { index, element in
var str = dictionary[index] ?? ""
str += element
dictionary[index] = str
}
}
}
where dictionary.values() will be desired elements
Upvotes: 2
Reputation: 6213
Well if you want to create data from this raw data, you can do as like below
let names = ["A","B","C","D","E"]
let element2 = [17945,10091,10088,3907,10132]
let element3 = [2,12,13,48,11]
struct DataModel {
var name : String
var id1 : String
var id2 : String
}
var allElements: [DataModel] = []
for i in zip(names, zip(element2, element3)) {
let model = DataModel(name: i.0, id1: i.1.0.description, id2: i.1.1.description)
allElements.append(model)
}
Upvotes: 2