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

4

7

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
Coheman answered 14/10, 2014 at 17:59 Comment(2)
do you mean swiftarray at the last line of code?Proficient
Check out this post by Matt Long: cimgf.com/2014/11/05/…Slack
C
11

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
Coheman answered 14/10, 2014 at 18:14 Comment(0)
E
8

I've found this:

var array = swiftarray.map({$0["key.path"]! as ObjectType})
Employment answered 7/6, 2015 at 11:52 Comment(0)
T
2

you can do the following:

let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>
Turmoil answered 17/5, 2016 at 12:29 Comment(0)
D
1

How about this:

let names = array.map { $0.name }

Instead of using key paths you can directly refer to property or method.

Diplegia answered 4/2, 2019 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.