Swift
URL Conversion
String Manipulation
Programming Tutorial
iOS Development

How to convert this var string to URL in Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift, converting a String to a URL is easy when the string is already a valid URL literal, but many real inputs are only URL-like. The safe approach depends on what the string contains: a complete URL, a path component, or query data that still needs percent encoding.

The Basic Conversion

For a fully formed URL string, use the failable initializer URL(string:).

swift
1import Foundation
2
3let text = "https://example.com/profile"
4let url = URL(string: text)
5
6print(url as Any)

This returns an optional because not every string is a valid URL. That means you should handle failure rather than force unwrap blindly.

swift
1import Foundation
2
3let text = "https://example.com/profile"
4
5if let url = URL(string: text) {
6    print(url)
7} else {
8    print("Invalid URL")
9}

If the input already is a valid absolute URL, this is usually enough.

Why Some Strings Fail

A lot of strings fail because they contain spaces or characters that should have been percent-encoded.

swift
1import Foundation
2
3let badText = "https://example.com/search?q=swift url"
4print(URL(string: badText) as Any)

That string looks close to valid, but the space in the query is a problem. The mistake is thinking every visually readable URL string is already syntactically valid.

Use URLComponents for Safer Construction

When you are building a URL from separate pieces, URLComponents is usually better than string concatenation because it handles encoding of query items correctly.

swift
1import Foundation
2
3var components = URLComponents()
4components.scheme = "https"
5components.host = "example.com"
6components.path = "/search"
7components.queryItems = [
8    URLQueryItem(name: "q", value: "swift url")
9]
10
11if let url = components.url {
12    print(url)
13}

This is the most reliable choice when the input is not already a complete, valid URL string.

Converting a File Path Is Different

If the string is a local file-system path, use URL(fileURLWithPath:) instead of URL(string:).

swift
1import Foundation
2
3let path = "/Users/markqian/Documents/report.pdf"
4let fileURL = URL(fileURLWithPath: path)
5
6print(fileURL)

This distinction matters because file URLs and web URLs are not created the same way. Using URL(string:) for a path often produces the wrong result or nil.

Relative URLs Need a Base

Sometimes the string is only a relative path such as "images/logo.png". In that case, create the base URL first and resolve the relative part against it.

swift
1import Foundation
2
3let base = URL(string: "https://example.com/assets/")!
4let relative = URL(string: "images/logo.png", relativeTo: base)
5
6print(relative?.absoluteURL as Any)

That is cleaner than manually joining path strings and helps avoid malformed slashes.

When Percent Encoding Helps

If you truly have a nearly complete URL string and just need to encode certain parts, percent encoding can help, but it should be used carefully.

swift
1import Foundation
2
3let rawQuery = "swift url"
4let encodedQuery = rawQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
5
6if let encodedQuery,
7   let url = URL(string: "https://example.com/search?q=\(encodedQuery)") {
8    print(url)
9}

This is acceptable for specific components such as a query value. It is usually less clean than URLComponents when you are assembling several parts.

Common Pitfalls

  • Force unwrapping URL(string:) even though invalid input can return nil.
  • Using URL(string:) on a local file path instead of URL(fileURLWithPath:).
  • Building URLs with raw string concatenation and forgetting percent encoding.
  • Trying to encode a whole finished URL string blindly instead of encoding the specific component that needs it.
  • Assuming that a string that looks readable to a human is automatically a valid URL.

Summary

  • Use URL(string:) when the string already is a valid full URL.
  • Handle the optional result safely because invalid input returns nil.
  • Use URLComponents when building URLs from parts, especially with query items.
  • Use URL(fileURLWithPath:) for local file paths.
  • Prefer structured URL construction over raw string concatenation when the input contains spaces or special characters.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.