URLPattern: A Swift Macro that helps mapping URLs to Enum cases

Overview

URL deep linking is a fundamental technology widely used in most services today. However, in Swift environments, implementing deep linking typically requires direct URL path manipulation or regex usage:

// Traditional approach with manual URL handling
let paths = url.pathComponents

if paths.count == 2 && paths[1] == "home" {
  // Handle home
} else let match = try? url.path.firstMatch(of: /\/posts\/([^\/]+)$/) {
  // Handle posts
}

This approach reduces code readability and scalability, and importantly, cannot validate incorrect patterns at compile-time.

URLPattern solves these issues by providing compile-time URL validation and value mapping:

@URLPattern
enum DeepLink {
  @URLPath("/home")
  case home
    
  @URLPath("/posts/{postId}")
  case post(postId: String)
    
  @URLPath("/posts/{postId}/comments/{commentId}")
  case postComment(postId: String, commentId: String)
}

Key features

:white_check_mark: Validates URL patterns at compile-time
:magnifying_glass_tilted_left: Ensures correct mapping between URL parameters and enum cases
:hammer_and_wrench: Supports String, Int, Float, Double parameter types

Check it out on GitHub: URLPattern

Feedback welcome! Thanks you

7 Likes