The += operator on Array corresponds to Array.extend which takes a SequenceType and not an individual element. If you wrap dict in an Array, then += will work:
people += [dict]
However, it's simpler and probably more efficient to use the append function instead:
people.append(dict)
Side note:
I'm not sure why you're using Any as the Array's element type and the Dictionary's value type (and maybe you have a good reason), but you should typically avoid that if at all possible. In this case I'd declare dict as [String: String] and people as [[String: String]]:
var people = [[String: String]]()
class Database {
class func addPerson(dict: [String : String]) -> Void {
people.append(dict)
}
}
Database.addPerson(["name" : "Fred"])
If you need to be able to store multiple types in your Dictionary, there are a few ways you can do that.
- Use an
NSDictionary directly.
- Declare the
Dictionary as [String: AnyObject].
- Use an
enum with associated values as the value type (this is usually the best option in Swift if you only need to support a few types because everything stays strongly typed).
Quick example of using an enum (there are quite a few examples of this technique in other SO questions):
enum DictValue {
case AsString(String)
case AsInt(Int)
}
var people = [[String: DictValue]]()
class Database {
class func addPerson(dict: [String : DictValue]) -> Void {
people.append(dict)
}
}
Database.addPerson(["name" : DictValue.AsString("Fred")])
Database.addPerson(["name" : DictValue.AsInt(1)])