Swift中如何将person数组内myPerson为true的元素添加到myPeople数组
实现addMyPeople函数的解决方案
你可以利用Swift的filter方法筛选出符合条件的人员,以下是两种常见实现方式:
方式一:直接替换myPeople数组(覆盖原有内容)
这种方式会将myPeople更新为仅包含people数组中myPerson为true的人员:
func addMyPeople(){ myPeople = people.filter { $0.myPerson } }
方式二:向myPeople数组追加符合条件的人员
如果不想覆盖myPeople原有内容,而是追加新的符合条件人员,可以这样写:
func addMyPeople(){ let eligiblePeople = people.filter { $0.myPerson } myPeople.append(contentsOf: eligiblePeople) }
测试示例
你可以修改peopleData里的myPerson值来验证效果:
var peopleData = [ person(name: "Bob", age: 22, job: "Student", myPerson: true), // 设为true,会被筛选出来 person(name: "John", age: 26, job: "Chef", myPerson: false) ]
内容的提问来源于stack exchange,提问作者user16680387
相关产品推荐
相关产品推荐

