class Employee: NSObject {
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
}
}
let employeeArray = [
Employee(id: 1, firstName: "Jon", lastName: "Skeet"),
Employee(id: 2, firstName: "Darin", lastName: "Dimitrov"),
Employee(id: 4, firstName: "Hans", lastName: "Passant")
]
// below examples show us extract the ids of all those objects in that array into a new array.
// 1. Using map method
let idArray = employeeArray.map({ (employee: Employee) -> Int in
employee.id
})
let idArray2 = employeeArray.map { $0.id } // also works
print(idArray2) // prints [1, 2, 4]
// 2. Using for loop
var idArrayFL = [Int]()
for employee in employeeArray {
idArrayFL.append(employee.id)
}
print(idArrayFL) // prints [1, 2, 4]
// 3. Using while loop
var idArrayWL = [Int]()
var iterator = employeeArray.makeIterator()
while let employee = iterator.next() {
idArrayWL.append(employee.id)
}
print(idArrayWL) // prints [1, 2, 4]
// 4. Using KVC and NSArray's value(forKeyPath:) method
// For this example we need to expand class with NSObject
let employeeNSArray = employeeArray as NSArray
if let idArrayKVC = employeeNSArray.value(forKeyPath: #keyPath(Employee.id)) as? [Int] {
print(idArrayKVC) // prints [1, 2, 4]
}
// 5. Using Collection protocol extension and AnyIterator
extension Collection where Iterator.Element: Employee {
func getIDs() -> Array<Int> {
var index = startIndex
let iterator: AnyIterator<Int> = AnyIterator {
defer { index = self.index(index, offsetBy: 1) }
return index != self.endIndex ? self[index].id : nil
}
return Array(iterator)
}
}
let idArrayCollection = employeeArray.getIDs()
print(idArrayCollection) // prints [1, 2, 4]