String+SwiftyMarkdown.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. //
  2. // String+SwiftyMarkdown.swift
  3. // SwiftyMarkdown
  4. //
  5. // Created by Simon Fairbairn on 08/12/2019.
  6. // Copyright © 2019 Voyage Travel Apps. All rights reserved.
  7. //
  8. import Foundation
  9. /// Some helper functions based on this:
  10. /// https://stackoverflow.com/questions/32305891/index-of-a-substring-in-a-string-with-swift/32306142#32306142
  11. extension StringProtocol {
  12. func index<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
  13. range(of: string, options: options)?.lowerBound
  14. }
  15. func endIndex<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
  16. range(of: string, options: options)?.upperBound
  17. }
  18. func indices<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Index] {
  19. var indices: [Index] = []
  20. var startIndex = self.startIndex
  21. while startIndex < endIndex,
  22. let range = self[startIndex...]
  23. .range(of: string, options: options) {
  24. indices.append(range.lowerBound)
  25. startIndex = range.lowerBound < range.upperBound ? range.upperBound :
  26. index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
  27. }
  28. return indices
  29. }
  30. func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<String.Index>] {
  31. var result: [Range<Index>] = []
  32. var startIndex = self.startIndex
  33. while startIndex < endIndex,
  34. let range = self[startIndex...]
  35. .range(of: string, options: options) {
  36. result.append(range)
  37. startIndex = range.lowerBound < range.upperBound ? range.upperBound :
  38. index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
  39. }
  40. return result
  41. }
  42. }