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 PathComponents to create a new PathPrefix value. It matches against prefixes of a URL’s pathComponents property.

    Given the Path type matches against URL.path why does PathPrefix wrap an array and match against URL.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”.

    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 given URL.

    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 of url.pathComponents. Otherwise, false.

  • Represents a path component for use in creating a PathPrefix. A path component can be either a name (which is matched for equality with the strings of a URL’s pathComponents) or a wildcard (which matches any non-nil value):

    PathPrefix([.name("/"), .wildcard, .name("bar")])
    

    To reduce noise, PathComponent conforms to ExpressibleByStringLiteral. So the above can be more simply expressed as:

    PathPrefix(["/", .wildcard, "foo"])
    

    See also

    PathPrefix
    See more

    Declaration

    Swift

    enum PathComponent