URL.ParseStrategy
A parse strategy for creating URLs from formatted strings.
Declaration
struct ParseStrategyOverview
Create an explicit URL.ParseStrategy to parse multiple strings according to the same parse strategy. The following example creates a customized strategy, then applies it to multiple URL candidate strings.
let strategy = URL.ParseStrategy(
scheme: .defaultValue("https"),
user: .optional,
password: .optional,
host: .required,
port: .optional,
path: .required,
query: .required,
fragment: .optional)
let urlStrings = [
"example.com?key1=value1", // no scheme or path
"https://example.com?key2=value2", // no path
"https://example.com", // no query
"https://example.com/path?key4=value4", // complete
"//example.com/path?key5=value5" // complete except for default-able scheme
]
let urls = urlStrings.map { try? strategy.parse($0) } // [nil, nil, nil, Optional(https://example.com/path?key4=value4), Optional(https://example.com/path?key5=value5)]You don’t need to instantiate a parse strategy instance to parse a single string. Instead, use the URL initializer init(_:strategy:), passing in a string to parse and a customized strategy, typically created with one of the static accessors. The following example parses a URL string, with a custom strategy that provides a default value for the port component if the source string doesn’t specify one.
let urlString = "https://internal.example.com/path/to/endpoint?key=value"
let url = try? URL(urlString, strategy: .url
.port(.defaultValue(8080))) // https://internal.example.com:8080/path/to/endpoint?key=value