Sajeel
Sajeel

Reputation: 168

Swift get first letter from property in array of custom objects

I have a custom object

class Keyword
{
    var keyword : String
    var description : String

    init(keywordID : Int, keyword : String, description : String)
    {
        self.keyword = keyword;
        self.description = description;
    }
}

And its data's like

var keywords = [Keyword]()
keywords.append(Keyword(keyword: "abc", description: "dsd dfgdf dghj"))
keywords.append(Keyword(keyword: "adet", description: "dsd dfgdf dghj"))
keywords.append(Keyword(keyword: "niuk", description: "dsd dfgdf dghj"))
keywords.append(Keyword(keyword: "sdg", description: "dsd dfgdf dghj"))
keywords.append(Keyword(keyword: "sax", description: "dsd dfgdf dghj"))
keywords.append(Keyword(keyword: "trygh", description: "dsd dfgdf dghj"))

For creating sections in UITableView, I need to have the first letter as the section title. For the above example I need the data as below

  1. a -> abc, adet
  2. n -> niuk
  3. s -> sdg, sax
  4. t -> trygh

I created another object to store the above data

class KeywordSection
{
    var section : Character
    var keywords : [Keyword]

    init(section : Character, keywords : [Keyword])
    {
        self.section = section;
        self.keywords = keywords;
    }
}

I did this in Android by looping through the array and extract the first letter and checking the sections. Also I need to check if the first letter is alphabet, if so I have to add that section, else the section will be '#' (same as that of iphone contacts app)

Upvotes: 3

Views: 1413

Answers (3)

vadian
vadian

Reputation: 285150

Nowadays (Swift 4+) grouping to sections became very comfortable

let grouped = Dictionary(grouping: keywords, by: { String($0.keyword.first!) })

and map it to a KeywordSection array

let sections = grouped.map({ KeywordSection(section: Character($0.0), keywords: $0.1) }).sorted{$0.section < $1.section}

Upvotes: 1

Urvish Modi
Urvish Modi

Reputation: 1138

Swift 4:

let newArray = arrayName.map{Array($0.name)[0]}

This will be character array. Use below syntax for get string.

String(newArray[index])

Upvotes: 1

Aderstedt
Aderstedt

Reputation: 6518

Add this method to your keyword class:

var sectionName : String {
    return keyword.substringToIndex(1) ?? "?"
}

Then use this code to create the dictionary of section headers to keywords:

var sections = [String:[Keyword]]()

for k in keywords {
    let s = k.sectionName
    if let oldKeywords = sections[s] {
        var mutableOldKeywords = oldKeywords
        mutableOldKeywords.append(k)
        sections[s] = mutableOldKeywords
    } else {
        sections[s] = [k]
    }
}

Upvotes: 3

Related Questions