1

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
}

2 Answers 2

1

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]
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

dictionary[firstChar].append(yourElement)

Since dictionary[firstChar] should get you your array

1 Comment

There are two problems with this. 1) dictionary key lookup returns an optional so you can’t call append on the result, you need to unwrap the optional first via chaining or map or similar, and 2) the array needs to be initialized before you can append to it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.