1

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"])

2 Answers 2

3

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

3 Comments

As a side note, is it possible to accept multiple types into a dictionary? ex [String: String or Int]()
There are 2 ways to do that: use NSDictionary or declare the dictionary as [String : AnyObject]. In both cases, values can be any reference type (so not restricted to string and int only)
There are the two methods that @Antonio mentioned and one other. I edited my answer with some more info.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.