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
2
  • do you mean swiftarray at the last line of code? Commented Oct 14, 2014 at 18:05
  • Check out this post by Matt Long: cimgf.com/2014/11/05/… Commented Jun 30, 2015 at 16:38

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

8

I've found this:

var array = swiftarray.map({$0["key.path"]! as ObjectType})

Comments

2

you can do the following:

let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>

Comments

1

How about this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.