Swift 5 ofrece muchas formas de obtener una matriz de valores de propiedad de una matriz de objetos similares. Según sus necesidades, puede elegir uno de los siguientes seis ejemplos de código de Playground para resolver su problema.
1. map
Método de uso
Con Swift, los tipos que se ajustan al Sequence
protocolo tienen un map(_:)
método. El siguiente código de muestra muestra cómo usarlo:
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]
2. Usando for
bucle
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]
3. Usando while
bucle
Tenga en cuenta que con Swift, entre bastidores, un for
bucle es solo un while
bucle sobre sequence
el iterador de a (consulte IteratorProtocol para obtener más detalles).
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]
4. Uso de una struct
que se ajusta a IteratorProtocol
y Sequence
protocolos
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]
5. Usando la Collection
extensión de protocolo yAnyIterator
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]
Tenga en cuenta que este ejemplo requiere class Employee
heredar de NSObject
.
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]
}
map
hace: transforma una matriz deEmployee
en una matriz deInt
, llena con elid
campo. Lo que equivale a decir "extraer el campo id de todas las instancias deEmployee
y ponerlas en una matriz"