NSAttributedString+Merge.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. //
  2. // NSAttributedString+Merge.swift
  3. // SwiftTheme
  4. //
  5. // Created by kcramer on 3/31/18.
  6. // Copyright © 2018 kcramer. All rights reserved.
  7. //
  8. import Foundation
  9. extension NSAttributedString {
  10. // Initialize a new attributed string from an existing attributed string,
  11. // merging the specified attributes.
  12. // The specified attributes overwrite existing attributes with the
  13. /// same keys. All other attributes are preserved.
  14. convenience init(attributedString attrStr: NSAttributedString,
  15. merging newAttributes: [NSAttributedString.Key: Any]) {
  16. let newString = NSMutableAttributedString(attributedString: attrStr)
  17. let range = NSMakeRange(0, attrStr.length)
  18. newString.enumerateAttributes(in: range, options: []) {
  19. (currentAttributes, range, _) in
  20. let mergedAttributes = currentAttributes.merge(with: newAttributes)
  21. newString.setAttributes(mergedAttributes, range: range)
  22. }
  23. self.init(attributedString: newString)
  24. }
  25. }
  26. // Merge a dictionary into another dictionary, returning a new dictionary.
  27. // The values of the other dictionary overwrite the values of the current
  28. // dictionary.
  29. private extension Dictionary {
  30. func merge(with dict: Dictionary) -> Dictionary {
  31. return dict.reduce(into: self) { (result, pair) in
  32. let (key, value) = pair
  33. result[key] = value
  34. }
  35. }
  36. }