ios 从对象数组中获取属性值数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28393334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:44:20  来源:igfitidea点击:

Get an array of property values from an object array

iosarraysswift

提问by Isuru

There's a class called Employee.

有一个班级叫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
    }
}

And I have an array of Employeeobjects. What I now need is to extract the ids of all those objects in that array into a new array.

我有一个Employee对象数组。我现在需要的是id将该数组中所有这些对象的s提取到一个新数组中。

I also found this similar question. But it's in Objective-C so it's using valueForKeyPathto accomplish this.

我也发现了这个类似的问题。但它在 Objective-C 中,所以它valueForKeyPath用来完成这个。

How can I do this in Swift?

我怎样才能在 Swift 中做到这一点?

回答by Antonio

You can use the mapmethod, which transform an array of a certain type to an array of another type - in your case, from array of Employeeto array of Int:

您可以使用该map方法,该方法将某种类型的数组转换为另一种类型的数组 - 在您的情况下,从数组 ofEmployee到数组Int

var array = [Employee]()
array.append(Employee(id: 4, firstName: "", lastName: ""))
array.append(Employee(id: 2, firstName: "", lastName: ""))

let ids = array.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 { 
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]
.id } // also works print(idArray) // prints [1, 2, 4]
.id }

回答by Imanou Petit

Swift 5 offers many ways to get an array of property values from an array of similar objects. According to your needs, you may choose one of the six following Playground code examplesto solve your problem.

Swift 5 提供了许多方法来从一组相似的对象中获取一组属性值。根据您的需要,您可以选择以下六个 Playground 代码示例之一来解决您的问题。



1. Using mapmethod

一、使用map方法

With Swift, types that conform to Sequenceprotocol have a map(_:)method. The following sample code shows how to use it:

在 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")
]

var idArray = [Int]()
var iterator = employeeArray.makeIterator()    
while let employee = iterator.next() {
    idArray.append(employee.id)
}
print(idArray) // prints [1, 2, 4]


2. Using forloop

2. 使用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
    }

}

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]


3. Using whileloop

3. 使用while循环

Note that with Swift, behind the scenes, a forloop is just a whileloop over a sequence's iterator (see IteratorProtocolfor more details).

请注意,对于 Swift,在幕后,for循环只是while在 asequence的迭代器上的循环(有关更多详细信息,请参阅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
    }

}

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]


4. Using a structthat conforms to IteratorProtocoland Sequenceprotocols

4. 使用struct符合IteratorProtocolSequence协议的

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]
}


5. Using Collectionprotocol extension and AnyIterator

5.使用Collection协议扩展和AnyIterator

##代码##

6. Using KVC and NSArray's value(forKeyPath:)method

6.使用KVC andNSArrayvalue(forKeyPath:)方法

Note that this example requires class Employeeto inherit from NSObject.

请注意,此示例需要class EmployeeNSObject.

##代码##