A lightweight Swift path pattern matcher for URL-style routing — supports named parameters, optional segments, and splat wildcards.
Add CodeMirror to your project using Xcode:
- In Xcode, go to
File→Add Package Dependencies... - Enter the repository URL:
https://github.com/jaywcjlove/swift-path-to.git - Click
Add Package
Or add it to your Package.swift file:
dependencies: [
.package(url: "https://github.com/jaywcjlove/swift-path-to.git", from: "1.0.0")
]- Named parameters:
:namecaptures a single path segment. - Optional segments:
{/:id}marks a single segment as optional. - Splat/wildcard:
*restcaptures remaining segments into an array.
import PathToParameters match arbitrary strings in a path by matching up to the end of a segment or up to any subsequent tokens. They are defined by prefixing the parameter name with a colon (:foo).
let fn = PathTo.match("/:foo/:bar")
if let r = fn("/test/route") {
// r -> params: ["foo": "test", "bar": "route"]
print(r.path) // "/test/route"
print(r.params["foo"] as? String) // "test"
print(r.params["bar"] as? String) // "route"
}Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo).
let fn = PathTo.match("/*splat")
if let r2 = fn("/bar/baz") {
// r -> params: ["splat": ["bar", "baz"]]
print(r2.params["splat"] as? [String]) // ["bar", "baz"]
}Braces can be used to define parts of the path that are optional.
let fn = PathTo.match("/users{/:id}/delete")
print(fn("/users/delete")?.params) // [:]
print(fn("/users/123/delete")?.params) // ["id": "123"]Licensed under the MIT License.