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
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
I've found this:
var array = swiftarray.map({$0["key.path"]! as ObjectType})
you can do the following:
let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With