user2413621
user2413621

Reputation: 2956

How to check if a variable is nil

I have a variable

var a: [AnyObject? -> Void] 

and I am adding data in to it by append method. Now I want to check if the variable is nil or not. I tried using [] but not working and also tried "", this also not working, can anyone tell what is the meaning of this variable and how to check if it is nil.

Upvotes: 7

Views: 45130

Answers (6)

Aditya Sharma
Aditya Sharma

Reputation: 605

In Swift 3.0

if let imageURL = dictObj["list_image"] as? String {
   print(imageURL)
}

Upvotes: 2

Leo Dabus
Leo Dabus

Reputation: 236538

Update: Xcode 7.3 Swift 2.2

If you want to check if a variable is nil you should use if let to unwrap if for you. There is no need to create a second var.

let str = "123"
var a = Int(str)        
if let a = a {
    print(a)
}

Or

if let a = Int(str) {
    print(a)
}

Upvotes: 7

cph2117
cph2117

Reputation: 2681

For me none of the above solutions worked when I was using an AVFoundation object.

I would get Type 'AVCaptureDeviceInput does not conform to protocol 'BooleanType' when I tried if (audioDeviceInput) and I would get Binary operator '!=' cannot be applied to operands of type 'AVCaptureDeviceInput' and 'nil'.

Solution in my situation

if (audioDeviceInput.isEqual(nil))

nil is a pointer like any other and can be referenced as such, which is why this works.

Upvotes: 0

Dhruv Ramani
Dhruv Ramani

Reputation: 2643

You can use if let. if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value.

var a:Int=0
if let b=a{
   println(a)
} else {
   println("Value - nil")
}

But for Strings you can also use .isEmpty() If you have initialized it to "".

var str:String=""
if !str.isEmpty(){
   println(str)
}

Upvotes: 1

Shreyash Mahajan
Shreyash Mahajan

Reputation: 23606

In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.

So, You can check it with below code:

let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()

if convertedNumber != nil {
    println("convertedNumber contains some integer value.")
}
// prints "convertedNumber contains some integer value."

Please refer this about nil for more information.

Upvotes: 2

Vinzzz
Vinzzz

Reputation: 11724

As far as I understand, var a is an Array of functions that take an optional Object of any type, and return void. So these functions's parameter IS optional, but the Array itself isn't : it cannot be nil, or it would be declared [AnyObject? -> Void]? , no?

EDIT : if, nevertheless, you declared this a as an optional (but WHY would you do that ?) - adding a ? - you check an optional existence with if let :

if let b = a {
// a not nil, do some stuff
} else {
// a is null
}

If you just want to check if the array is empty, use isEmpty method from Swift Array

Upvotes: 16

Related Questions