Key-Value Coding (KVC) with Array/Dictionary in Swift

喜你入骨 提交于 2019-11-30 09:48:16

It seems that KVC on native Swift objects is just not supported. Here's the most elegant workaround I've found:

var swiftarray: Array = []
// Fill the array with objects
var array: NSArray = (swiftarray as NSArray).valueForKeyPath("key.path") as NSArray

I've found this:

var array = swiftarray.map({$0["key.path"]! as ObjectType})

you can do the following:

let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>

How about this:

let names = array.map { $0.name }

Instead of using key paths you can directly refer to property or method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!