String+Sweeter.swift 1021 B

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // String+Sweeter.swift
  3. //
  4. // Created by Yonat Sharon on 2019-02-08.
  5. //
  6. import Foundation
  7. extension String {
  8. /// Sweeter: Separate CamelCase into capitalized words.
  9. /// E.g., "winterIsComing" -> "Winter Is Coming"
  10. public var unCamelCased: String {
  11. return replacingCamelCase(with: "$1 $2").capitalized
  12. }
  13. /// Sweeter: Change CamelCase into snake_case
  14. /// E.g., "winterIsComing" -> "winter_is_coming"
  15. public var camelToSnakeCased: String {
  16. return replacingCamelCase(with: "$1_$2").lowercased()
  17. }
  18. func replacingCamelCase(with template: String) -> String {
  19. return String.camelCaseWordBoundaryRegex
  20. .stringByReplacingMatches(in: self, range: NSRange(startIndex..., in: self), withTemplate: template)
  21. }
  22. static let camelCaseWordBoundaryRegex: NSRegularExpression = {
  23. do {
  24. return try NSRegularExpression(pattern: "([a-z])([A-Z])")
  25. } catch {
  26. fatalError(error.localizedDescription)
  27. }
  28. }()
  29. }