Skip to content

Instantly share code, notes, and snippets.

@olgusirman
Created July 10, 2019 15:23
Show Gist options
  • Save olgusirman/fe84dd3b05e3e3b318bfc041e3fee741 to your computer and use it in GitHub Desktop.
Save olgusirman/fe84dd3b05e3e3b318bfc041e3fee741 to your computer and use it in GitHub Desktop.
These manager gets that array inside array and sorted and separate from first letter
protocol Letterable {
var name: String { get }
}
final class LetterManager<T: Letterable> {
// MARK : - Publics
func getTheFirstLetters(with section: Int) -> String {
var allTitles = [String]()
for initials in dictionaryWithInitials {
allTitles.append(initials.key)
}
if allTitles.indices.contains(section) {
return allTitles[section]
}
return ""
}
var dictionaryWithInitials = [(key: String, value: [T])]()
// MARK: - Privates
private let datas: [T]
private var initials = [String]() //Array that includes starter letter
init(datas: [T]) {
self.datas = datas
getTheInitials(from: datas)
filterInitialsDependsOnTheFirstLetter()
}
private func getTheInitials(from datas:[T]) {
for brand in datas {
// Need a check here, just in case
let initial = "\(brand.name.capitalized.first!)"
// If there is no initial letter add it
if initials.contains(initial) == false {
initials.append(initial)
}
}
}
private func filterInitialsDependsOnTheFirstLetter() {
for initial in initials { //Başharflere göre markaları ayır
let filteredBrands = datas.filter({ (brandObject) -> Bool in
let first = "\(brandObject.name.capitalized.first!)"
if first == initial {
return true
}
return false
})
let tuple = (initial,filteredBrands)
dictionaryWithInitials.append(tuple)
}
self.dictionaryWithInitials = dictionaryWithInitials.sorted(by: { $0.0 < $1.0 }) //sort the array depends on the first letter
}
}
// Usage
/*
struct SomeObject: Letterable {
var name: String
}
let aldo = SomeObject(name: "Aldo")
let aldo2 = SomeObject(name: "Aldo2")
let baldo = SomeObject(name: "Baldo")
let caldo = SomeObject(name: "Caldo")
var datas : [SomeObject] = [aldo, aldo2, baldo, caldo]
let manager = LetterManager<SomeObject>(datas: datas)
manager.dictionaryWithInitials
manager.getTheFirstLetters(with: 2)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment