'How do you pass data dynamically is a Swift array?

Im creating a tinder like swipe app and I need a new CardData(name: "", age: "") to be created depending on how many profiles I pass through from my database. The number of cards will change. I need the number of cards created to match the the value of the results default. I have looked for the solution for a while and can't find it anywhere.

import UIKit


var nameArrayDefault = UserDefaults.standard.string(forKey: "nameArray")!
var ageArrayDefault = UserDefaults.standard.string(forKey: "ageArray")!

var nameArray = nameArrayDefault.components(separatedBy: ",")
var ageArray = ageArrayDefault.components(separatedBy: ",")

var results = UserDefaults.standard.string(forKey: "results")!

struct CardData: Identifiable {

let id = UUID()

let name: String

let age: String

static var data: [CardData] {[
        
CardData(name: “\(nameArray[0])”, age: “\(ageArray[0])”),
CardData(name: “\(nameArray[1])”, age: “\(ageArray[1])"),
CardData(name: “\(nameArray[2])”, age: “\(ageArray[2])”)

]}

}


Solution 1:[1]

You should initiate the array of CardData objects only the first time and update it after that. You can do the following

var _data = [CardData]()
var data: [CardData] {
       if _data.isEmpty() {
             self.initiateData()
       }
       return _data
}

// Initiate data for the first time only
func initiateData() -> [CardData] {
    // Check that nameArray has the same size as ageArray
    // If the size is different then the data are not valid. 
    guard nameArray.count == ageArray.count else {
         return []
    }

    // For each of names inside nameArray create the corresponding CardData object
    self.nameArray.forEach({ (index, item)
         self._data.append(CardData(name: item, age: ageArray[index]))
    })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Arnok