user83039
user83039

Reputation: 3167

Dictionary containing Arrays containing Dictionaries?

Code snippets:

This is from a struct called Static:

static var messages: Dictionary = [:]

This is inside a class function:

if Static.messages[sender] == nil{ //no message history, create array then append
    var messages: [NSMutableDictionary] = [message]
    Static.messages[sender] = messages
}
else{ //there is message history, so append
    (Static.messages[sender] as Array).append(message)
}

Error:

Immutable value of type 'Array<T>' only has mutating members named 'append'

I'm trying to make a Dictionary of conversations with each item being a person. Each array will be a list of messages. The messages are of type dictionary. Any idea why I'm getting this message?

Upvotes: 1

Views: 90

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

If you're clear with the compiler about what your dictionary contains, you won't need the cast that is making this difficult. From what you've posted, the actual type of Static.messages will need to be something like Dictionary<NSObject, Array<NSMutableDictionary>>.

Your current attempt casts a dictionary value as an Array and then tries to append -- this fails because Swift treats the result of this kind of cast as immutable. What you need to do instead is to simply use optional chaining:

// instead of:
(Static.messages[sender] as Array).append(message)

// use:
Static.messages[sender]?.append(message)

Upvotes: 2

Related Questions