Peter71 Peter71 - 1 year ago 72
Swift Question

List in dictionary as a template definition

I'm using arrays which are stored in a dictionray for fast access. Because I need this logic for different data types, I like to define it as a template, but I don't have any idea how to pass types. In my own description it should look like this:

struct KeyList {
let key : MyType1
var list = [MyType2]()

init(key : MyType1, value : MyType2) {
self.key = key

var dicList = [String: KeyList]()

value = ...of MyType2
key = ... of MyType1

if dicList[key] == nil {
// new entry
dicList[key] = KeyList(key: key, value: value)
else {
// add it to existing list

But I want to use Swift 3. Any idea, if this is possible?

Answer Source

You'll need a couple of things:

  1. generics
  2. encapsulation


Here's an example

struct Container<Key, Value> where Key: Hashable {

    private var dict: [Key:[Value]] = [:]

    func list(by key: Key) -> [Value]? {
        return dict[key]

    mutating func add(value: Value, to key: Key) {
        dict[key] = (dict[key] ?? []) + [value]



Now you can create a Container specifying the Key and the Value types

var container = Container<String, Int>()
container.add(value: 1, to: "a")
container.add(value: 2, to: "a")
container.list(by: "a") // [1, 2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download