Search code examples
swifturl

What is consider a bad URL


Shouldn't this code print out failed

func dummyFetch()  {
    let urlString = "as-2k2i2i asdfadsf;kkaqfkqj; q;klef ;k;lqke"
    guard let _ = URL(string: urlString) else {
        print("failed")
        return
    }
    print("passed")
}

Cause right now it is printing out passed for me. Im a little confused, what will need to be passed in the urlString to print out failed?


Solution

  • what will need to be passed in the urlString to print out failed

    Here's an example of a string that will result in a nil URL:

    let url = URL(string: "h t t p://what")
    

    Here's a less drastic example:

    let url = URL(string: "")
    

    It's positively useful to have strings of this sort on hand, because sometimes you need to unit test something that should fail coherently on being given a bad URL string.