chirag shah chirag shah - 5 months ago 25x
Swift Question

check NSURLConnection variable is not nil

I am new in swift and i want to find that NSURLConnection variable is nil or not. We used following code in Objective c.

if (urlConnection) {
// Do somethings

But if i right same in swift it give me error like

" Type NSURLConnection dose not conform to protocol


If you just want to check if it’s non-nil, urlConnection != nil will do the trick. Note, if urlConnection is not an optional, you cannot check it for nil. This is a good thing. If something isn’t optional in Swift, it means it cannot possibly be nil, it must have a value, and therefore the check is redundant – there’s no need for it, you can freely use the value without needing to check it.

However, you most likely want to check if it’s nil, and if it isn’t, then use it. In which case, you want:

if let urlcon = urlConnection {
    // urlcon will be the “unwrapped” non-nil value 
else {
    // if you want handling code for it it’s nil, it goes here

Alternatively, if you don’t care about handling the value not being nil, the following might work for your use case:


This tests if urlConnection is non-nil, and if it is, calls doSomething(). The one thing to note is that any value you get back from doSomething() will be wrapped in an optional, because urlConnection might have been nil and therefore there might be no result to look at.

You might occasionally see someone suggesting:

if urlConnection != nil {

If you do, take no advice from this person and avoid their code at all costs.