本文介绍了从对象数组中获取属性值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个类叫做Employee
.
class Employee {
var id: Int
var firstName: String
var lastName: String
var dateOfBirth: NSDate?
init(id: Int, firstName: String, lastName: String) {
self.id = id
self.firstName = firstName
self.lastName = lastName
}
}
而且我有一组 Employee
对象.我现在需要的是将该数组中所有对象的 id
提取到一个新数组中.
And I have an array of Employee
objects. What I now need is to extract the id
s of all those objects in that array into a new array.
我也发现了这个类似的问题.但是它在 Objective-C 中,所以它使用 valueForKeyPath
来完成这个.
I also found this similar question. But it's in Objective-C so it's using valueForKeyPath
to accomplish this.
如何在 Swift 中执行此操作?
How can I do this in Swift?
推荐答案
您可以使用 map
方法,该方法将某种类型的数组转换为另一种类型的数组 - 在您的情况下,从 Employee
数组到 Int
数组:
You can use the map
method, which transform an array of a certain type to an array of another type - in your case, from array of Employee
to array of Int
:
var array = [Employee]()
array.append(Employee(id: 4, firstName: "", lastName: ""))
array.append(Employee(id: 2, firstName: "", lastName: ""))
let ids = array.map { $0.id }
这篇关于从对象数组中获取属性值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!