Guest User

Untitled

a guest
May 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. item = dicMyList[key]
  2. if item != nil {
  3. // add it to existing list
  4. dicMyList[key]!.list.append(filename)
  5. // item?.list.append(filename)
  6. }
  7.  
  8. // example setup
  9. var dicMyList = [1: ["foo.sig", "bar.cc"]] // [Int: [String]] dict
  10. var key = 1
  11. var fileName = "baz.h"
  12.  
  13. // "append" (copy-in/copy-out) 'fileName' to inner array associated
  14. // with 'key'; constructing a new key-value pair in case none exist
  15. dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
  16. print(dicMyList) // [1: ["foo.sig", "bar.cc", "baz.h"]]
  17.  
  18. // same method used for non-existant key
  19. key = 2
  20. fileName = "bax.swift"
  21. dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
  22. print(dicMyList) // [2: ["bax.swift"], 1: ["foo.sig", "bar.cc", "baz.h"]]
  23.  
  24. if var list = dicMyList[key] {
  25. list.append(filename)
  26. dicMyList[key] = list
  27. } else {
  28. dicMyList[key] = [filename]
  29. }
  30.  
  31. extension Optional where Wrapped == Array<String> {
  32.  
  33. mutating func append(_ element: String) {
  34. if self == nil {
  35. self = [element]
  36. }
  37. else {
  38. self!.append(element)
  39. }
  40. }
  41. }
  42.  
  43. var dictionary = [String: [String]]()
  44.  
  45. dictionary["Hola"].append("Chau")
Add Comment
Please, Sign In to add comment