DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 970,177 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Swift Features: Static URL
Vadim Atamanenko
Vadim Atamanenko

Posted on

Swift Features: Static URL

Tired of using URL(string: "url")! for static urls? πŸ’‘Make the URL match ExpressibleByStringLiteral and you can just use "url".

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)")
    }
}
Enter fullscreen mode Exit fullscreen mode
// We can now define URLs using static string literals πŸŽ‰
let url: URL = "https://www.apple.com"
let task = URLSession.shared.dataTask(with: "https://www.apple.com")`
Enter fullscreen mode Exit fullscreen mode
// 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)
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

πŸŒ–πŸŒ—πŸŒ˜ Turn on dark mode in Settings