0

I have an array of objects, that I'm trying to filter down by several properties from that object. Below is a simplified object and loop to do what I need.
But I'm not getting a list of names, and when I do, I'm getting an extra ", " at the end even though I'm checking to make sure that the person is the last in array.

struct Person: Equatable {
    var name: String
    var gender: String
    var age: Int
    var address: String
}

var personArray: [Person] = [Person]()

personArray.append(Person(name: "Pedro", gender: "M", age: 23, address: "1 Lane Drive"))
personArray.append(Person(name: "Juan", gender: "M", age: 18, address: "1 Lane Drive"))
personArray.append(Person(name: "Mary", gender: "F", age: 13, address: "1 Lane Drive"))
personArray.append(Person(name: "Carlos", gender: "M", age: 21, address: "1 Lane Drive"))
personArray.append(Person(name: "Jesus", gender: "M", age: 15, address: "1 Lane Drive"))
personArray.append(Person(name: "Jaque", gender: "F", age: 35, address: "1 Lane Drive"))

var minors = ""

for person in personArray {
    if person.age < 18 && person.gender == "f" {
        minors.append(person.name)
        if person != personArray.last {
            minors.append(", ")
        }
    }
}
// if there are female minors, print list of minors
print(minors)

What I need is to be able to get a list of all minors or none if applicable.

1 Answer 1

3

You can simplify that by making it a bit more swifty:

let minors = personArray.filter({$0.age < 18 && $0.gender == "F"}).map({$0.name}).joined(separator: ", ")

if minors.isEmpty {
    print("There are no minors")
} else {
    print("List of minors: \(minors)")
}

The first problem for you is that you have a typo. Your gender is set as "F" but in your loop you're checking for "f".

Based on only the above info, I'm not sure if the "Equatable" on your struct is needed. The reason why the comparison for last isn't working is because you checking if the person is equal to the last object in the array, but the last object in array in this case does not match your requirements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.