Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key-Value Coding (KVC) with Array/Dictionary in Swift

Is it possible to key-value code (KVC) with native Swift data structures such as Array and Dictionary? Key-Value coding is still available for NSFoundation structures within Swift, just like in Objective C.

For example, this is valid:

var nsarray: NSArray = NSArray()
// Fill the array with objects
var array: NSArray = nsarray.valueForKeyPath("key.path")

But this is invalid:

var swiftarray: Array = []
// Fill the array with objects
var array = swiftarray.valueForKeyPath("key.path") // Invalid, produces a compile-time error
like image 402
kev Avatar asked Oct 14 '14 17:10

kev


3 Answers

It seems that KVC on native Swift objects is just not supported. Here's the most elegant workaround I've found:

var swiftarray: Array = []
// Fill the array with objects
var array: NSArray = (swiftarray as NSArray).valueForKeyPath("key.path") as NSArray
like image 148
kev Avatar answered Nov 19 '22 09:11

kev


I've found this:

var array = swiftarray.map({$0["key.path"]! as ObjectType})
like image 29
Phoenix Avatar answered Nov 19 '22 10:11

Phoenix


you can do the following:

let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>
like image 2
Grégoire Aubin Avatar answered Nov 19 '22 09:11

Grégoire Aubin