Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Using key-value programming (KVP) with Swift

In Objective-C with Cocoa a lot of tasks can be accomplished without explicit loops by using Key-Value Programming (KVP). For example, I can find the largest number in an array with a single line of code:

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

How can I do the same thing with swift? Arrays do not appear to support valueForKeyPath method.

Upvotes: 7

Views: 4296

Answers (4)

tassinari
tassinari

Reputation: 2363

You can also use the reduce function of Array

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

Upvotes: 2

Sam
Sam

Reputation: 5892

The array will actually respond to valueForKeyPath function - you just need to cast the array to AnyObject so that the compiler doesn't complain. As follows:

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

or even, for a union of objects:

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

If labels above is a collection of labels, the above will return an array of all the strings of the text property of each label.

It is also equivalent to the following:

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

... just as it is in Objective-C :)

Upvotes: 22

Rui Peres
Rui Peres

Reputation: 25917

You can still use (at least) the didSet willSet provided by Swift on properties. I guess it's better than nothing.

Upvotes: 1

Matt Bridges
Matt Bridges

Reputation: 49425

I'm not sure about KVP, but KVO isn't currently supported in Swift. See also this dev forums thread:

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

Upvotes: 0

Related Questions