tolerate_Me_Thx
tolerate_Me_Thx

Reputation: 387

How to sort by comparing with each characters in swift?

Sorry, I have a question about sort data.
I don't know how to sort each characters , I just sort by first characters like following image.
How can I sort characters in each section array.
Thanks.

enter image description here

var cityCollation: UILocalizedIndexedCollation? = nil
var sectionsCityArray = [[City]]()
var cityArray:[City] = [City]() //cityArray is my original data that is not sorting 

func configureSectionCity() { 

    cityCollation = UILocalizedIndexedCollation.current()

    let sectionTitlesCount = cityCollation!.sectionTitles.count

    var newSectionsArray = [[City]]()

    for _ in 0..<sectionTitlesCount {
        let array = [City]()
        newSectionsArray.append(array)
    }

    for bean in cityArray {
        let sectionNumber = cityCollation?.section(for: bean, collationStringSelector: #selector(getter: City.name))
        var sectionBeans = newSectionsArray[sectionNumber!]

        sectionBeans.append(bean)
        newSectionsArray[sectionNumber!] = sectionBeans
    }

  sectionsCityArray = newSectionsArray

  }

Upvotes: 0

Views: 92

Answers (1)

vadian
vadian

Reputation: 285064

Assuming the City object has a name property and you want the order q001, q002, q004, q005, q010, q012 you could use

newSectionsArray[sectionNumber!] = sectionBeans.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }

localizedStandardCompare requires the Foundation framework

Upvotes: 1

Related Questions