简体   繁体   English

使用Swift的键值编程(KVP)

[英]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). 在使用Cocoa的Objective-C中,通过使用键值编程(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? 我如何用swift做同样的事情? Arrays do not appear to support valueForKeyPath method. 数组似乎不支持valueForKeyPath方法。

The array will actually respond to valueForKeyPath function - you just need to cast the array to AnyObject so that the compiler doesn't complain. 该数组实际上将响应valueForKeyPath函数 - 您只需要将数组转换为AnyObject以便编译器不会抱怨。 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. 如果上面的labelslabels的集合,则上面的标签将返回每个标签的text属性的所有字符串的数组。

It is also equivalent to the following: 它也等同于以下内容:

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

... just as it is in Objective-C :) ......就像在Objective-C中一样:)

You can also use the reduce function of Array 您还可以使用Array的reduce函数

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 这里有好的解释

You can still use (at least) the didSet willSet provided by Swift on properties. 您仍然可以使用(至少)Swift在属性上提供的didSet willSet I guess it's better than nothing. 我想这比什么都没有好。

I'm not sure about KVP, but KVO isn't currently supported in Swift. 我不确定KVP,但Swift目前不支持KVO。 See also this dev forums thread: 另见这个dev论坛帖子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM