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
sを新しい配列に抽出することです。
また、これと同様の question が見つかりました。しかし、Objective-Cにあるため、valueForKeyPath
を使用してこれを実現しています。
Swiftでこれを行うにはどうすればよいですか?
map
メソッドを使用すると、特定の型の配列を別の型の配列に変換できます。この場合、Employee
の配列からInt
の配列に変換します。
var array = [Employee]()
array.append(Employee(id: 4, firstName: "", lastName: ""))
array.append(Employee(id: 2, firstName: "", lastName: ""))
let ids = array.map { $0.id }
Swift 5は、同様のオブジェクトの配列からプロパティ値の配列を取得する多くの方法を提供します。必要に応じて、問題を解決するためにPlaygroundのコード例の6つのいずれかを選択できます。
map
メソッドを使用するSwiftでは、Sequence
プロトコルに準拠する型には map(_:)
メソッドがあります。次のサンプルコードは、その使用方法を示しています。
class Employee {
let id: Int, firstName: String, lastName: String
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")
]
let idArray = employeeArray.map({ (employee: Employee) -> Int in
employee.id
})
// let idArray = employeeArray.map { $0.id } // also works
print(idArray) // prints [1, 2, 4]
for
ループを使用するclass Employee {
let id: Int, firstName: String, lastName: String
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")
]
var idArray = [Int]()
for employee in employeeArray {
idArray.append(employee.id)
}
print(idArray) // prints [1, 2, 4]
while
ループの使用Swiftでは、舞台裏で、for
ループはwhile
のイテレーターに対するsequence
ループにすぎません(詳細については IteratorProtocol を参照してください)。
class Employee {
let id: Int, firstName: String, lastName: String
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")
]
var idArray = [Int]()
var iterator = employeeArray.makeIterator()
while let employee = iterator.next() {
idArray.append(employee.id)
}
print(idArray) // prints [1, 2, 4]
struct
およびIteratorProtocol
プロトコルに準拠するSequence
を使用するclass Employee {
let id: Int, firstName: String, lastName: String
init(id: Int, firstName: String, lastName: String) {
self.id = id
self.firstName = firstName
self.lastName = lastName
}
}
struct EmployeeSequence: Sequence, IteratorProtocol {
let employeeArray: [Employee]
private var index = 0
init(employeeArray: [Employee]) {
self.employeeArray = employeeArray
}
mutating func next() -> Int? {
guard index < employeeArray.count else { return nil }
defer { index += 1 }
return employeeArray[index].id
}
}
let employeeArray = [
Employee(id: 1, firstName: "Jon", lastName: "Skeet"),
Employee(id: 2, firstName: "Darin", lastName: "Dimitrov"),
Employee(id: 4, firstName: "Hans", lastName: "Passant")
]
let employeeSequence = EmployeeSequence(employeeArray: employeeArray)
let idArray = Array(employeeSequence)
print(idArray) // prints [1, 2, 4]
Collection
プロトコル拡張とAnyIterator
を使用するclass Employee {
let id: Int, firstName: String, lastName: String
init(id: Int, firstName: String, lastName: String) {
self.id = id
self.firstName = firstName
self.lastName = lastName
}
}
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 employeeArray = [
Employee(id: 1, firstName: "Jon", lastName: "Skeet"),
Employee(id: 2, firstName: "Darin", lastName: "Dimitrov"),
Employee(id: 4, firstName: "Hans", lastName: "Passant")
]
let idArray = employeeArray.getIDs()
print(idArray) // prints [1, 2, 4]
NSArray
の- value(forKeyPath:)
メソッドの使用この例では、NSObject
から継承するためにclass Employee
が必要であることに注意してください。
import Foundation
class Employee: NSObject {
@objc let id: Int, firstName: String, lastName: String
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")
]
let employeeNSArray = employeeArray as NSArray
if let idArray = employeeNSArray.value(forKeyPath: #keyPath(Employee.id)) as? [Int] {
print(idArray) // prints [1, 2, 4]
}