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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 从对象数组中获取属性值数组相关的知识,希望对你有一定的参考价值。

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]

以上是关于swift 从对象数组中获取属性值数组的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 3.0 中,没有在数组中的索引处获取对象的键值语法

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

从嵌套属性数组中获取对象嵌套值

TS / JS-如果对象的属性与数组中的另一个属性相匹配,则从对象数组中获取“值”

通过属性值从对象数组中获取JavaScript对象[重复]

通过属性值从对象数组中获取JavaScript对象[重复]