import Foundation
// A nested struct representing an address
struct Address {
let city: String
let zip: Int
}
// A struct representing a person, containing a nested Address
struct Person {
let name: String
let age: Int
let address: Address
}
// Print each person in a formatted line
func printPersons(_ people: [Person]) {
for p in people {
print("\(p.name) | age: \(p.age) | city: \(p.address.city) | zip: \(p.address.zip)")
}
}
// Sort persons by city, then zip, then age
func sortPersons(_ people: [Person]) -> [Person] {
people.sorted {
if $0.address.city != $1.address.city {
return $0.address.city < $1.address.city
}
if $0.address.zip != $1.address.zip {
return $0.address.zip < $1.address.zip
}
return $0.age < $1.age
}
}
// Sample data
let people: [Person] = [
Person(name: "Alice", age: 30, address: Address(city: "San Francisco", zip: 42100)),
Person(name: "Bob", age: 40, address: Address(city: "Austin", zip: 32000)),
Person(name: "Carol", age: 35, address: Address(city: "New York City", zip: 42000)),
Person(name: "Dave", age: 25, address: Address(city: "Austin", zip: 32000)),
Person(name: "Eve", age: 28, address: Address(city: "New York City", zip: 61000))
]
// Perform sorting
let sorted = sortPersons(people)
// Display sorted results
printPersons(sorted)
/*
run:
Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100
*/