Search code examples
iosswiftnssortdescriptor

Sorting fetched results


I'm fetching some objects from core data. One of the properties is a name identifier. The names can be either text or a number, so the property is a String type. What I'd like to be able to do is sort it so that the text objects are first, then the numbers in numerical order.

Currently its putting the numbers first, and the numbers are in the wrong order, ie. 300, 301, 3011, 304, 3041, Blanc, White

let sortDescriptor = NSSortDescriptor(key: "number", ascending: true)   
fetchRequest.sortDescriptors = [sortDescriptor]

Solution

  • Naive version:

    let fetchedResults = ["300", "301", "3011", "304", "3041", "Blanc", "White"]
    
    var words = [String]()
    var numbers = [String]()
    
    for value in fetchedResults {
        if let number = Int(value) {
            numbers.append(value)
        } else {
            words.append(value)
        }
    }
    
    let result = words + numbers
    print(result)
    

    Prints:

    ["Blanc", "White", "300", "301", "3011", "304", "3041"]