简体   繁体   中英

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.

It seems to be a combination of several problems:

  • The collation must be created with UILocalizedIndexedCollation.currentCollation() .
  • The object class needs an instance method returning a String .
  • The #selector must refer to that instance method, both #selector(<Type>.<method>) and #selector(<instance>.<method>) can be used.

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.

For solving of your issue at first read new documentation about Selectors in Swift2.2.

Example: Use #selector(CLASS.lastName) instead of Selector("lastName") . Where CLASS it is actual class that contains this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM