how do I get NSSortDescriptors to work in Swift 4?

Viewed 1813

I am struggling to get NSSortDescriptors to work on my mac tables.
I did a quick proof of concept below and it still shows the same error:

Error ProofSortDescriptors[19446:1951711] Failed to set (contentViewController) user defined inspected property on (NSWindow): [<_SwiftValue 0x60400007c180> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name. ( name is the name of the property of the struct)

Could it be to do with the change in way that Swift 4 bridges Objective C?

would be great to get this working on Mac Swift

Here is my attempt:

import Cocoa
struct Customer {
    var name:String
    var value:Int
}
class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let cust1 = Customer(name: "bob", value: 100)
        let cust2 = Customer(name: "cat", value: 200)
        let cust3 = Customer(name: "dog", value: 300)

        var custcol = [cust2, cust3, cust1]
        let descrip = NSSortDescriptor(key: "name", ascending: true)
        let sorted = (custcol as NSArray).sortedArray(using: [descrip])
        var sortedCustomers = sorted as? [Customer]
        print(sortedCustomers!)
    }

}
4 Answers

swift 4

For sorting custom class array using NSSortDescriptors in swift 4, you need to declare class as below.

@objcMembers class Customer:NSObject {
    var name:String!
    var value:Int!
}
Related