swiftPunk
swiftPunk

Reputation: 1

How can I Extract an Array from an Array of custom struct in Swift?

I am making a struct called personStruct, which takes simple data like age and name. Here is this struct:

struct personStruct
{
    var name: String = String()
    var age: Int = Int()
}

then I am using this down class for extracting my wished arrays:

class PersonModel
{
    
    var persones: [personStruct] = [personStruct]()
    var countOfPersones: Int { persones.count }
    
    
    
    func personesAgeArray() -> [Int]
    {
        var returnArray: [Int] = [Int]()
        for item in persones { returnArray.append(item.age) }
        return returnArray
    }
    
    func personesNameArray() -> [String]
    {
        var returnArray: [String] = [String]()
        for item in persones { returnArray.append(item.name) }
        return returnArray
    }
   
}

And this is my use case of those struct and class:

let personModel: PersonModel = PersonModel()
personModel.persones = [personStruct(name: "bob", age: 30), personStruct(name: "Roz", age: 26), personStruct(name: "man", age: 40)]
print(personModel.personesAgeArray())
print(personModel.personesNameArray())

So as you see that class make that Job done!

My Goal: Do we have a real syntax or more efficiency way for making those Arrays? (I mean personesAgeArray and personesNameArray)

My Super Goal: I want personesAgeArray and personesNameArray get automatically builded/updated with adding new item to persones.

Upvotes: 0

Views: 991

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236370

struct Person {
    let name: String
    let age: Int
}

class Model {
    var people: [Person] = []
    var peopleCount: Int { people.count }
    var ages: [Int] { people.map(\.age) }
    var names: [String] { people.map(\.name) }
}

let model: Model = .init()
model.people = [.init(name: "bob", age: 30), .init(name: "Roz", age: 26), .init(name: "man", age: 40)]
print(model.ages)  // "[30, 26, 40]\n"
print(model.names) // "["bob", "Roz", "man"]\n"
model.people.append(.init(name: "Omid", age: 20))
print(model.ages)  // "[30, 26, 40, 20]\n"
print(model.names) // "["bob", "Roz", "man", "Omid"]\n"

Upvotes: 2

Related Questions