Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 146 · Standard Library and Foundation

UUID, URL and URLComponents

Create UUIDs and parse, build and encode URLs in Swift - URL parts, relative URLs, URLComponents, URLQueryItem, percent-encoding, the plus-sign trap and safe construction of web addresses.

Two small Foundation types appear in almost every real app. A UUID is a unique label you can create without asking anyone: database ids, file names, request ids, the key of a row in a list. A URL is an address, and web programming is mostly about building addresses correctly, with the right slashes, the right question mark and the right escaping, and taking them apart again.

Building URLs by gluing strings together is a classic source of bugs: a space in a search term, an ampersand in a name or a missing slash produces a broken or even dangerous address. Swift gives you URL for the finished address and URLComponents for building and editing one piece at a time. This lesson also explains percent-encoding, the plus-sign trap that bites many programmers, and Swift 6's new, more forgiving URL(string:). You should know optionals and strings.

UUID: a unique identifier

A UUID is a 128-bit number, usually written as 32 hexadecimal digits in groups: E621E1F8-C36C-495A-93FC-0C247A3E6E5F. UUID() makes a new random one (version 4). There are so many possible values that a clash is practically impossible, so independent machines can create ids without coordinating.

Swift Creating and parsing UUIDs

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A string form always has 36 characters (32 digits plus 4 hyphens). Two UUID() calls never match, so the comparison prints false, and a set of three holds three. UUID(uuidString:) is failable: it accepts upper or lower case, but returns nil for text that is not exactly the hyphenated form, and also for the 32 digits without hyphens. The uuidString property is always uppercase; lowercase it yourself when a system such as a database or an API expects lowercase. A UUID is Hashable, Codable (it encodes as its uppercase string) and Sendable, so it works as a dictionary key and in JSON. Under the hood it is a tuple of 16 bytes, which .uuid exposes (230 and 95 are the first and last bytes of the example).

A random UUID is an identifier, not a secret. Do not use one as a password-reset token or an API key. Use a longer secret from a cryptographic source for that. Also, random UUIDs sort randomly, which can slow database indexes; some systems prefer time-ordered ids for that reason.

URL: an address with parts

URL(string:) parses text into a URL. Each part of the address is a property: scheme, host, port, user, password, path, query, fragment. Most are optional because an address may lack them.

Swift The parts of a URL

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The scheme is https, the host example.com, the port 8443. The path is /docs/swift/intro.html and does not include the query or fragment. query is the raw text lang=en&page=2&q=a%20b (still escaped), and fragment is section-3. pathComponents splits the path with the leading / as its first element. Removing the last component keeps the query and fragment attached. Not every URL is a web address: mailto: has a scheme and a path but no host.

Relative URLs and adding path pieces

A URL can be relative to a base, the way a link ../img/a.png on a page is resolved against the page's address. And appending(path:) extends a URL with correct slash handling and automatic escaping.

Swift Relative URLs and appending paths

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The relative link resolves to https://example.com/docs/img/a.png: the browser rule walks up one folder from /docs/swift/. The baseURL remembers the page it was resolved against. appending(path:) produces https://example.com/users/42 without you worrying about a doubled or missing /, and escapes spaces in my files/report 1.pdf (the printed address has %20). appending(queryItems:) adds ?q=swift.

Why URL(string:) returns an optional

Text that is not a valid address cannot become a URL, so the initializer is failable. In Swift 6 the parser became more forgiving: it percent-encodes characters that are not allowed instead of rejecting them.

Swift Which text becomes a URL?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An empty string gives nil. A string with a space is now accepted and escaped to has%20space, and café becomes caf%C3%A9. Passing encodingInvalidCharacters: false restores the strict behavior and returns nil. A bad host such as exa mple.com is still rejected by URLComponents. The scheme keeps the case you typed (HTTPS), so compare schemes with lowercased().

Never hide a possible failure with ! on text that comes from users, files or the network. The crash happens at run time:

Swift Force-unwrapping an invalid URL (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program ends with SIGILL and a backtrace pointing at main. Use guard let url = URL(string: text) else { ... } and report the problem. A force unwrap is fine only for a constant you wrote yourself and tested, such as URL(string: "https://example.com")!.

Forgetting to unwrap is caught by the compiler, which is the better kind of failure:

Swift Using an optional URL directly (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:4:7: error: value of optional type 'URL?' must be unwrapped to refer to member 'host' of wrapped base type 'URL'

URLComponents: read and build addresses safely

URLComponents holds the parts as editable properties and assembles the URL for you, escaping each part according to its own rules. For anything with a query string, it is the right tool. Query values live in queryItems, an array of URLQueryItem (name and an optional value).

Swift Reading a query string

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each pair becomes an item. Repeated names are kept, so tag appears twice, and you can collect them with filter. A parameter with an empty value (empty=) gives Optional(""), while a bare flag with no = gives a nil value, which differs from empty. Values arrive as strings, so convert numbers yourself, with flatMap(Int.init) to stay optional. Keep a helper that looks up a parameter by name; it is the part you write in every project.

Building a URL

To create a URL, start with an empty URLComponents, set the pieces, and read url. Never put raw user text into a string template.

Swift Building a URL with query items

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The query is q=salt%20%26%20pepper%20%3D%20taste&limit=10&city=Z%C3%BCrich: the & and = inside the first value are escaped to %26 and %3D, spaces to %20 and ü to %C3%BC, so the structure of the query survives. An item with no value prints as a bare name (extra). percentEncodedPath shows the escaped path, path the readable one. Finally, a path that does not start with / while a host is present is invalid, and url returns nil: always check the result.

The plus-sign trap

In HTML form submissions, a space in a query is written as +. In plain URL rules, + is just a plus. Foundation follows the plain rules: it does not escape + when writing a query, and does not turn + into a space when reading one. A value like 1+1 can therefore be misread as 1 1 by a server that follows the form convention.

Swift Plus signs in query values

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first URL contains expr=1+1, which a form-style server reads as "1 1". After replacing the plus in the encoded query, you get expr=1%2B1. Reading ?q=a+b gives the value a+b, not a b, so if you consume form-encoded queries, replace + with a space yourself. The helper at the end uses a strict allowed set (letters, digits and -._~), the only characters that never need escaping, and prints q=swift%20%26%20c%2B%2B&lang=fran%C3%A7ais.

Percent-encoding by hand

A percent-encoded character is written as % plus two hex digits for each UTF-8 byte: a space is %20, é is %C3%A9. String has two methods for it, and the character set you allow decides what stays as it is. Different parts of a URL allow different characters, so there is no one correct set.

Swift addingPercentEncoding with different sets

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

.urlQueryAllowed leaves &, / and + alone, which is why it is a poor choice for a single query value: the ampersand would split the pair. .alphanumerics escapes everything except letters and digits, which is safe for a value but also escapes /, . and -. Decoding reverses it (a b/c), and malformed input such as %zz gives nil. standardized removes . and .. segments, but it does not lowercase the host. And a trailing slash makes two URLs different (false), so normalize before you compare or use them as cache keys.

Prefer URLComponents and URLQueryItem to manual encoding whenever you can, and write a custom allowed set only for the plus-sign case or for a format such as OAuth that needs strict escaping.

File URLs versus web URLs

URL(fileURLWithPath:) makes a file:// URL from a path, and (unlike URL(string:)) it escapes spaces for you. Use url.path to get the plain path back, and use url.absoluteString only for display. The files lesson uses this constantly.

Swift
let file = URL(fileURLWithPath: "/tmp/a b.txt")
print(file.absoluteString)   // file:///tmp/a%20b.txt
print(file.path)             // /tmp/a b.txt

Do not pass a file path to URL(string:); URL(string: "/tmp/a b.txt") makes a URL with no scheme, which most APIs reject.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does UUID().uuidString return?

    The canonical string form is 8-4-4-4-12 hexadecimal digits in uppercase.
  2. 2. Why does URL(string:) return an optional?

    Invalid text such as an empty string cannot become a URL, so the initializer is failable. Do not force-unwrap text you did not write.
  3. 3. What is the most reliable way to add salt & pepper as a query value?

    URLComponents escapes each part according to its own rules, so & and = in a value cannot break the query.
  4. 4. A query contains expr=1+1. What does a server using the form convention read?

    Foundation does not escape +. Replace it with %2B in the encoded query when the value must contain a plus.
  5. 5. What does queryItems give for the URL https://x.com/?flag?

    A name without = has a nil value, while flag= has an empty string.

Summary

  • UUID() creates a random unique id; uuidString is uppercase and 36 characters; UUID(uuidString:) is failable. A UUID is an identifier, not a secret.
  • URL(string:) is failable. Swift 6 percent-encodes spaces and non-ASCII characters instead of rejecting them (pass encodingInvalidCharacters: false for strict parsing). Never force-unwrap untrusted text.
  • Read parts with scheme, host, port, path, query, fragment, lastPathComponent and pathExtension; build paths with appending(path:).
  • URLComponents with URLQueryItem is the safe way to read and create query strings; a nil value (?flag) differs from an empty one (?flag=).
  • Foundation does not escape + in queries or decode it as a space; handle this explicitly when form-style servers are involved.
  • addingPercentEncoding(withAllowedCharacters:) depends on the character set you choose; trailing slashes and .. segments make equal addresses compare unequal until normalized.
  • File paths belong in URL(fileURLWithPath:), not URL(string:).

Next: Processes and Environment shows how a program reads its arguments, environment variables and exit code.