Hodson Hodson - 1 year ago 134
Swift Question

How to purposely create a malformed URL in Swift

I have the following Swift extension on


public extension NSURL {

func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else {
return nil

guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name == key


I am writing unit tests for it but I am unable to get 100% code coverage as I don't seem to be able to get
NSURLComponents(URL: self, resolvingAgainstBaseURL: false)
to return
. From what I understand, this requires a malformed URL but I am struggling to create one.

I have tried:

  • let url = NSURL(string: "")

  • let url = NSURL(string: "http://www.example")

  • let url = NSURL(string: "http://www.exam ple.com")

  • let url = NSURL(string: "http://www.example.com/?param1=äëīòú")

And some others that I lost track of. I know this is probably something blatantly obvious but i'm lost at the moment. So, how do I create a malformed URL in Swift?

Answer Source

As found in my research, you can produce a url that is malformed for NSURLComponents but not for NSURL by using negative port number (probably there are more cases but not sure):

let example = "http://example.com:-80/"
let url = NSURL(string: example)
print("url:\(url)") //prints out url:Optional(http://example.com:-80/)
if let url = url {
    let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
    print("comps:\(comps)") //prints out comps:nil
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download