Articles, podcasts and news about Swift development, by John Sundell.

Defining static URLs using string literals

Published on 17 Jul 2017
Basics article available: Strings

Tired of using URL(string: "url")! for static URLs? Make URL conform to ExpressibleByStringLiteral and you can now simply use "url" instead.

extension URL: ExpressibleByStringLiteral {
    // By using 'StaticString' we disable string interpolation, for safety
    public init(stringLiteral value: StaticString) {
        self = URL(string: "\(value)").require(hint: "Invalid URL string literal: \(value)")

// We can now define URLs using static string literals 🎉
let url: URL = ""
let task = URLSession.shared.dataTask(with: "")

// In Swift 3 or earlier, you also have to implement 2 additional initializers
extension URL {
    public init(extendedGraphemeClusterLiteral value: StaticString) {
        self.init(stringLiteral: value)

    public init(unicodeScalarLiteral value: StaticString) {
        self.init(stringLiteral: value)

To find the extension that adds the require() method on Optional that I use above, check out Require.

Support Swift by Sundell by checking out this sponsor:


Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.