如何在一组结构实例中查找某些属性的匹配项?

时间:2017-02-03 21:51:29

标签: swift struct

我正在试验Swift 3中的结构并试图提取/打印一些值。这是我的代码:

struct person {
    var name: String
    var gender: String
    var age: Int
}

var people = [
    person(
        name: "Steve",
        gender: "Male",
        age: 25
    ),
    person(
        name: "Paul",
        gender: "Male",
        age: 30
    ),
    person(
        name: "Sandra",
        gender: "Female",
        age: 21
    ),
    person(
        name: "Becky",
        gender: "Female",
        age: 30
    ),
    person(
        name: "Trevor",
        gender: "Male",
        age: 45
    )
]

我了解到,如果我提供age,我可以找到name个人:

let nameToSearch = "Trevor"

if let i = people.index(where: {$0.name == nameToSearch}) {
    print("\(nameToSearch) is aged \(people[i].age)") // Trevor is aged 45
}

最好的方法是什么......

1)捕获组中四个最老的人,按年龄按降序排序,然后打印出来?

Trevor is aged 45
Paul is aged 30
Becky is aged 30
Steve is aged 25

2)捕获gender"Male"的所有实例,然后将其打印出来?

The males are Steve, Paul, Trevor

出于兴趣,假设用户正在执行导致获取/设置现有实例的操作,以及添加/删除实例,person中存在大量people个实例数组会导致应用程序性能受到影响吗?

2 个答案:

答案 0 :(得分:1)

一种简洁的方式来吸引4位最老的人:

let oldestPeople = people.sorted(by: { $0.0.age > $0.1.age })[0 ..< 4]
for person in oldestPeople {
    print("\(person.name) is aged \(person.age)")
}

获得男性名字:

let maleNames = people.filter({ $0.gender == "Male" }).map({ $0.name })
print("The males are " + maleNames.joined(separator: ", "))

答案 1 :(得分:0)

感谢您指导我朝着正确的方向迈凯什。这是我的解决方案。为了得到四个最老的人:

var personAndAge = [String: Int]()

people.forEach {
    personAndAge[$0.name] = $0.age
}

var increment = 0
let limit = 4

for (person, age) in personAndAge.sorted(by: { $0.1 > $1.1 }) {
    increment = increment + 1
    if (increment <= limit) {
        print("\(person) is aged \(age)")
    }
}

/*
prints:
Trevor is aged 45
Becky is aged 30
Paul is aged 30
Steve is aged 25
*/

仅限男性:

let peopleFilteredToMales = people.filter { $0.gender == "Male"}
var maleNames: [String] = []
peopleFilteredToMales.forEach { maleNames.append($0.name) }
let outputString = "The males are " + maleNames.joined(separator: ", ")
print(outputString)

// prints: The males are Steve, Paul, Trevor