PathPrefix
public struct PathPrefix : URLMatchable
Type that matches a URL
based on the prefix of the URL
’s pathComponents
property.
Usage:
let url = URL(string: "http://example.com/foo/bar")!
PathPrefix(["/", "foo", "bar"]).matches(url) //> true
PathPrefix(["/", .wildcard, "bar"]).matches(url) //> true
PathPrefix(["/", "foo"]).matches(url) //> true
See also
Path
-
Wraps the given
PathComponent
s to create a newPathPrefix
value. It matches against prefixes of aURL
’spathComponents
property.Given the
Path
type matches againstURL.path
why doesPathPrefix
wrap an array and match againstURL.pathComponetns
? Because matching a partial path is a common source of bugs.Consider the URL “example.com/foo/bar”. We may wish to match only the “/foo” part so we naïvely create a value like
PostPrefix("/foo")
. This looks straight-forward, but also matches “example.com/foox”. Even if we catch this and use the (easy to overlook)PostPrefix("/foo/")
we now have a situation where “example.com/foo” doesn’t match because lacks the trailing"/"
.Requiring an array of path components not only forces us to think through these issues but also has the virtuous property of making the naïve solution the correct one —
PathPrefix(["/", "foo"])
matches both “example.com/foo/bar” and “example.com/foo” but does not match “example.com/foox”.See also
In the common case of matching against an absolute
URL
, don’t forget the first element of path components must be a"/"
.Declaration
Swift
public init(_ pathComponents: [PathComponent])
Parameters
components
The prefix of the path components to match.
-
Predicate that determines whether a
PathPrefix
matches a givenURL
.Declaration
Swift
public func matches(url: URL) -> Bool
Parameters
url
The
URL
to be matched.Return Value
true
if the wrapped path components are a prefix ofurl.pathComponents
. Otherwise,false
.
-
Represents a path component for use in creating a
PathPrefix
. A path component can be either aname
(which is matched for equality with the strings of aURL
’spathComponents
) or awildcard
(which matches any non-nil value):PathPrefix([.name("/"), .wildcard, .name("bar")])
To reduce noise,
PathComponent
conforms toExpressibleByStringLiteral
. So the above can be more simply expressed as:PathPrefix(["/", .wildcard, "foo"])
See also
PathPrefix
Declaration
Swift
enum PathComponent