Using Key Programming (KVP) with Swift

In Objective-C with Cocoa, many tasks can be performed without explicit loops using key value programming (KVP). For example, I can find the largest number in an array with one line of code:

NSNumber * max = [numbers valueForKeyPath:@"@max.intValue"]; 

How can I do the same with quick? Arrays do not support the valueForKeyPath method.

+7
swift
source share
4 answers

The array will actually respond to the valueForKeyPath function - you just need to pass the array to AnyObject so that the compiler does not complain. As below:

 var max = (numbers as AnyObject).valueForKeyPath("@max.self") as Double 

or even to combine objects:

 (labels as AnyObject).valueForKeyPath("@unionOfObjects.text") 

If labels above is a set of labels, then an array of all lines of the text property of each label will be returned above.

It is also equivalent to the following:

 (labels as AnyObject).valueForKey("text") 

... just like in Objective-C :)

+22
source share

You can still use (at least) didSet willSet provided by Swift on properties. I think this is better than nothing.

+1
source share

You can also use the array reduction function

 let numbers = [505,4,33,12,506,21,1,0,88] let biggest = numbers.reduce(Int.min,{max($0, $1)}) println(biggest) // prints 506 

Good explanation here

+1
source share

I'm not sure about KVP, but KVO is not currently supported in Swift. See also this forum:

https://devforums.apple.com/thread/227909

0
source share

All Articles