iosswiftcocoauilocalizedcollation

Swift 2.2 string literal selector


Before the update I this code worked fine:

var alphabetizedArray = [[Person]]()

    let collation = UILocalizedIndexedCollation()

    for person : Person in ContactsManager.sharedManager.contactList {
        var index = 0
        if ContactsManager.sharedManager.sortOrder == .FamilyName {
            index = collation.sectionForObject(person, collationStringSelector: "lastName")
        }
        else {
            index = collation.sectionForObject(person, collationStringSelector: "firstName")
        }
        alphabetizedArray.addObject(person, toSubarrayAtIndex: index)
    }

But now since string literal selectors are no longer alowed the code broke.

I tried to change string literal selector to Selector("lastName"), but the 'index' is always returned as -1. And I don't see any solution.

This collation method takes a property name of the given object. And Person class is really have those properties (lastName, firstName).

But how can I get this work again? Experiments with #selector gave me nothing: 'Argument of '#selector' does not refer to an initializer or method' it says. No wonder since this sectionForObject(, collationStringSelector:) takes no methods but a property names.


Solution

  • It seems to be a combination of several problems:

    Here is a self-contained example which seems to work as expected:

    class Person : NSObject {
        let firstName : String
        let lastName : String
    
        init(firstName : String, lastName : String) {
            self.firstName = firstName
            self.lastName = lastName
        }
    
        func lastNameMethod() -> String {
            return lastName
        }
    }
    

    and then

    let person = Person(firstName: "John", lastName: "Doe")
    let collation = UILocalizedIndexedCollation.currentCollation()
    let section = collation.sectionForObject(person, collationStringSelector: #selector(Person.lastNameMethod))
    print(section) // 3
    

    Here, both #selector(Person.lastNameMethod) and #selector(person.lastNameMethod) can be used.