0

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 'BooleanType'"

Kumar KL
  • 15,315
  • 9
  • 38
  • 60
Chirag Shah
  • 3,034
  • 1
  • 30
  • 61
  • possible duplicate of [NSURLConnection Using iOS Swift](http://stackoverflow.com/questions/24176362/nsurlconnection-using-ios-swift) – Paresh Navadiya Mar 05 '15 at 13:20

3 Answers3

0

If your urlConnection its typed of NSURLConnection? then you can check it by doing this

if (urlConnection != nil) {
   // Do somethings
}

If your urlConnection its typed of NSURLConnection then its never nil

Zell B.
  • 10,266
  • 3
  • 40
  • 49
  • If it gives error only with this line then your urlConnection its never nil and its type its non optional. If it gives error when you try to use it inside if statement then probably you are not force unwrapping it by using `urlConnection!` – Zell B. Mar 05 '15 at 13:25
0
if let data = urlConnection{
    //is not not nil
}
else{
    //is nil
}
IxPaka
  • 1,990
  • 1
  • 16
  • 18
0

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:

urlConnection?.doSomething()

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 {
    urlConnection!.something()
}

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

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • thanks for your answer but i try with "if let urlcon = urlConnection" but it still give me the error like "Bound value in a conditional binding must be a optional part" – Chirag Shah Mar 05 '15 at 13:30
  • Right. The problem is `urlConnection` isn’t optional. This means it _cannot_ be nil. Just not a possibility. So you can’t check for it – but the good news is, you don’t need to! Just use it. – Airspeed Velocity Mar 05 '15 at 13:31