David
David

Reputation: 733

How can I add a dictionary to an array using Swift?

I'm trying to add a dictionary containing properties of people into an array, but it's not working. I'm getting the following error:

[(Any)] is not identical to UInt8

Here is my code:

var people = [Any]()

class Database {
    class func addPerson(dict: [String : Any]) -> Void {
        people += dict
    }
}

Database.addPerson(["name" : "Fred"])

Upvotes: 1

Views: 151

Answers (2)

Mike S
Mike S

Reputation: 42325

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.

  1. Use an NSDictionary directly.
  2. Declare the Dictionary as [String: AnyObject].
  3. 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)])

Upvotes: 3

Kirsteins
Kirsteins

Reputation: 27335

There is not built in operator for that I guess. You can use:

people.append(dict)
// or
people += [dict as Any]

Upvotes: 1

Related Questions