Maxime Thizeau
Maxime Thizeau

Reputation: 25

Array in Dictionary in Swift

My question is really simple and I guess it’s easy to do but, how to add an object into an array when the array is held in a dictionary in Swift language?

var dictionary = [String: [String]]()
for course in self.category.m_course_array
{
    let firstChar = String(Array(course.getTitle())[0]).uppercaseString
    dictionary[firstChar] =  // How to add an element into the array of String
}

Upvotes: 1

Views: 252

Answers (2)

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

Not so easy as you might think, in fact. It's is a bit messy since you need to handle the fact that when the key isn’t present, you need to initialize the array. Here’s one way of doing it (code altered to be similar but stand-alone):

var dictionary = [String: [String]]()
let courses = ["Thing","Other Thing","Third Thing"]

for course in courses {
    // note, using `first` with `if…let` avoids a crash in case
    // you ever have an empty course title
    if let firstChar = first(course).map({String($0).uppercaseString}) {
        // get out the current values
        let current = dictionary[firstChar]
        // if there were none, replace nil with an empty array,
        // then append the new entry and reassign
        dictionary[firstChar] = (current ?? []) + [course]
    }
}

Alternatively, if you want to use .append you could do this:

    // even though .append returns no value i.e. Void, this will
    // return Optional(Void), so can be checked for nil in case
    // where there was no key present so no append took place 
    if dictionary[firstChar]?.append(course) == nil {
        // in which case you can insert a single entry
        dictionary[firstChar] = [course]
    }

Upvotes: 1

IxPaka
IxPaka

Reputation: 2008

Try this

dictionary[firstChar].append(yourElement)

Since dictionary[firstChar] should get you your array

Upvotes: 0

Related Questions