Using key-value programming (KVP) with Swift

后端 未结 4 1149
既然无缘
既然无缘 2021-02-09 09:01

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

4条回答
  •  礼貌的吻别
    2021-02-09 09:41

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

提交回复
热议问题