nssortdescriptorswift4.2

NSSortDescriptor case sensitivity in Swift 4.2


I am trying to sort alphabetically without case sensitivity using NSSortDescriptor is Swift 4.2. Unfortunately, I have only found solutions in Objective-C.

func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")
    let sorter = NSSortDescriptor(key: "texttitle", ascending: true)

    fetchRequest.sortDescriptors = [sorter]
    return fetchRequest

}

Solution

  • Using caseInsensitiveCompare: (with the colon) does not work in Swift 4.2.

    This works:

    func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
    
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")
        let sorter = NSSortDescriptor(key: "texttitle", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
    
        fetchRequest.sortDescriptors = [sorter]
        return fetchRequest
    
    }