Peter71 Peter71 - 1 month ago 7
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
self.list.append(value)
}
}


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
dicList[key]!.list.append(value)
}
}


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

Answer

You'll need a couple of things:

  1. generics
  2. encapsulation

Snippet

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]
    }

}

Usage

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]