0

I am trying to check if array is initialized in Swift. I am working on iOS Programming Big Nerd Ranch Guide, the code is in objective C and I am trying to write that in swift. I need a way to check if the array in initialized or not please check the below code:

var items1:[string]  
var items2:[string]!

override init(){
    super.init()
    //how do i check if items1 or items2 is initialized 
    if(items1 == nil){ //this does not work
    //Initialize the array and do something with it!! 
    }
}

2 Answers2

1

If you have a property with ?(items1)or!(items2),you need to check if it is initialized or not.Because it can be nil

You do not check items3,because it have to be initialized in init method.

class TestClass:NSObject{
    var items1:[String]?;
    var items2:[String]!
    var items3:[String]

    override init() {
        items3 = [String]()
        super.init()
    }

    func testFunction(){
        if items1 == nil{

        }
        if items2 == nil{

        }
    }
}

You can check if an Array is empty with this

if items3.count == 0{

}

Or this

if items3.isEmpty{

}
tonchis
  • 598
  • 3
  • 10
Leo
  • 24,596
  • 11
  • 71
  • 92
  • The key point is that if you have a var or let that isn't optional, the compiler requires that you assign it a value in your initializer(s). If you don't your code won't compile. – Duncan C May 30 '15 at 02:50
  • That is the whole point of optional and required variables in swift. If it isn't optional, it can **never** be nil once the init method has executed. You can depend on it. – Duncan C May 30 '15 at 02:50
0

You can use the .isEmpty method to check for items. With the if let statement check if an object is initialized.

let array = Books(title: "Title")


if let newBook = array {
    println("A book was initialized with the title \(array.title)")
}
PoolHallJunkie
  • 1,345
  • 14
  • 33