A blog about Swift and iOS tricks

Defining URLs using String literals in Swift

Almost every URL out there is constructed using a string, while the Foundation provides a very convenient way to construct a URL from a string using URL(string:) still we can add some sugar to make it even easier to use!

extension URL: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        guard value.representingValidURL, let url = URL(string: "\(value)") else {
            fatalError("\(value) cannot be mapped to a url")
        }
        self = url
    }
}

private extension String {
    var representingValidURL: Bool {
        let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        if let match = detector?.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) {
            return match.range.length == self.utf16.count
        } else {
            return false
        }
    }
}

// You can use it as follows 
let url: URL = "https://www.alihilal.com"
let task = URLSession.shared.dataTask(with: url)