Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- item = dicMyList[key]
- if item != nil {
- // add it to existing list
- dicMyList[key]!.list.append(filename)
- // item?.list.append(filename)
- }
- // example setup
- var dicMyList = [1: ["foo.sig", "bar.cc"]] // [Int: [String]] dict
- var key = 1
- var fileName = "baz.h"
- // "append" (copy-in/copy-out) 'fileName' to inner array associated
- // with 'key'; constructing a new key-value pair in case none exist
- dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
- print(dicMyList) // [1: ["foo.sig", "bar.cc", "baz.h"]]
- // same method used for non-existant key
- key = 2
- fileName = "bax.swift"
- dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
- print(dicMyList) // [2: ["bax.swift"], 1: ["foo.sig", "bar.cc", "baz.h"]]
- if var list = dicMyList[key] {
- list.append(filename)
- dicMyList[key] = list
- } else {
- dicMyList[key] = [filename]
- }
- extension Optional where Wrapped == Array<String> {
- mutating func append(_ element: String) {
- if self == nil {
- self = [element]
- }
- else {
- self!.append(element)
- }
- }
- }
- var dictionary = [String: [String]]()
- dictionary["Hola"].append("Chau")
Add Comment
Please, Sign In to add comment