Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent for valueForKey: [duplicate]

This question is in regards to Swift collection types, not Objective-C NS collection types in Swift.

For example, how would I do this in Swift?

NSArray *items = // some JSON response
NSArray *names = [items valueForKey:"firstName"];

Note: This question is NOT a duplicate of the one many have marked as a duplicate of, because this question is about whether Swift has a new way of calling valueForKey: on Swift collection types. That question is about how to call valueForKey: in Swift on Objective-C NS collection types. In other words, this question addresses how to do things the new Swift way, rather than doing Swift the Objective-C way. Also, that question has no marked accepted answer.

like image 910
James Kuang Avatar asked Nov 21 '25 12:11

James Kuang


1 Answers

There is no valueForKey: in Swift, but there is a way to use map to achieve a similar, if not same, result.

Similar to valueForKey:

// items contains dictionaries
let names = items.map { $0["firstName"] as? String }

// items contains objects
let names = items.map{ $0.firstName }

Similar to valueForKeyPath:

let streets = items.map { $0["address"]?["street"] as? String }

Objective-C

For interoperability, you can also use a cast to continue using valueForKey: or valueForKeyPath:

let streets = (items as NSArray).valueForKeyPath("address.street") as? NSArray

If you are using Objective-C NS collection types like NSDictionary in Swift, then you can still continue to call valueForKey: in Swift syntax.

let names = items.valueForKey("firstName")
like image 61
James Kuang Avatar answered Nov 24 '25 03:11

James Kuang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!