URLPathComponent.swift 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. enum URLPathComponent {
  2. case plain(String)
  3. case placeholder(type: String?, key: String)
  4. }
  5. extension URLPathComponent {
  6. init(_ value: String) {
  7. if value.hasPrefix("<") && value.hasSuffix(">") {
  8. let start = value.index(after: value.startIndex)
  9. let end = value.index(before: value.endIndex)
  10. let placeholder = value[start..<end] // e.g. "<int:id>" -> "int:id"
  11. let typeAndKey = placeholder.components(separatedBy: ":")
  12. if typeAndKey.count == 1 { // any-type placeholder
  13. self = .placeholder(type: nil, key: typeAndKey[0])
  14. } else if typeAndKey.count == 2 {
  15. self = .placeholder(type: typeAndKey[0], key: typeAndKey[1])
  16. } else {
  17. self = .plain(value)
  18. }
  19. } else {
  20. self = .plain(value)
  21. }
  22. }
  23. }
  24. extension URLPathComponent: Equatable {
  25. static func == (lhs: URLPathComponent, rhs: URLPathComponent) -> Bool {
  26. switch (lhs, rhs) {
  27. case let (.plain(leftValue), .plain(rightValue)):
  28. return leftValue == rightValue
  29. case let (.placeholder(leftType, leftKey), .placeholder(rightType, key: rightKey)):
  30. return (leftType == rightType) && (leftKey == rightKey)
  31. default:
  32. return false
  33. }
  34. }
  35. }