Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using key-value programming (KVP) with Swift

Tags:

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.

like image 563
Sergey Kalinichenko Avatar asked Jun 04 '14 14:06

Sergey Kalinichenko


People also ask

What is key-value coding in Swift?

Key-value observing is a Cocoa programming pattern you use to notify objects about changes to properties of other objects. It's useful for communicating changes between logically separated parts of your app—such as between models and views. You can only use key-value observing with classes that inherit from NSObject .

Can you explain KVO?

KVO, which stands for Key-Value Observing, is one of the techniques for observing the program state changes available in Objective-C and Swift. The concept is simple: when we have an object with some instance variables, KVO allows other objects to establish surveillance on changes for any of those instance variables.

Which collection uses key pair value in Swift?

Swift provides three primary collection types for storing collection of values. They are: Arrays → ordered collections of values. Dictionaries → unordered collections of key-value pairs/associations.


2 Answers

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 :)

like image 105
Sam Avatar answered Oct 06 '22 20:10

Sam


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

like image 32
tassinari Avatar answered Oct 06 '22 18:10

tassinari