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

后端 未结 4 1676
小蘑菇
小蘑菇 2021-01-01 00:32

Is it possible to key-value code (KVC) with native Swift data structures such as Array and Dictionary? Key-Value coding is still available for NSFoundation structures within

相关标签:
4条回答
  • 2021-01-01 01:14

    you can do the following:

    let items : Array<String> = (myArray as AnyObject).valueForKeyPath("name") as! Array<String>
    
    0 讨论(0)
  • 2021-01-01 01:14

    How about this:

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

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

    0 讨论(0)
  • 2021-01-01 01:15

    I've found this:

    var array = swiftarray.map({$0["key.path"]! as ObjectType})
    
    0 讨论(0)
  • 2021-01-01 01:38

    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
    
    0 讨论(0)
提交回复
热议问题