ardakaraca ardakaraca - 4 months ago 17
Swift Question

How to create a struct from two arrays?

I have

SearchViewController
and I created "Data" class to load SearchViewController.

//File.swift
class Data {

var add1: String
var add2: String

init(add1: String, add2: String) {
self.add1 = add2
self.add1 = add2
}
}


//ViewController.swift
//This is the part that I want to load from two arrays of strings.
var entries = [Data]()

entries = [
Data(add1: "Canada", add2: "Ottawa"),
Data(add1: "USA", add2: "Washington"),
Data(add1: "Japan", add2: "Tokyo"),
Data(add1: "Denmark", add2: "Copenhagen")
]


My class for search controller's data list goes on. I'll have approx 1000 values. Therefore, I want to load this class from two arrays like shown below.

let arr1: [String] = ["Canada", "USA", "Japan", "Denmark"]
let arr2: [String] = ["Ottawa", "Washington", "Tokyo", "Copenhagen"]

Answer

try to iterate the value in loop and appends to the entries array

for i in 0..<arr1.count {
    // create struct from array data
    let data = Data(add1: arr1[i], add2: arr2[i])

    // insert to your array
    entries.append(data)           
}
Comments