0
import UIKit

class ViewController: UIViewController {
    var testArray:[String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        doThis(nil)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func doThis(completion:(() -> Void)?) {
        dispatch_async(dispatch_get_main_queue(), {() -> Void in
            if let completionBlock = completion {
                completionBlock()
            }

            self.testArray.append("first")
            print(self.testArray)
            if self.testArray == [] {
                print("has data")
            } else {
                print("null")
            }
        })
    }
}

Output:

["first"]
null

I was wondering why the array is nil?

Tim
  • 41,901
  • 18
  • 127
  • 145
stumped
  • 3,235
  • 7
  • 43
  • 76
  • http://stackoverflow.com/questions/19179358/concurrent-vs-serial-queues-in-gcd please look at this experiments..this will make you clear – LC 웃 Mar 21 '16 at 08:18

2 Answers2

2

The array is not nil. It cannot be nil because nil is one case of Optional, and the array isn't declared Optional.

Presumably you are wondering why your program prints null. It prints null because the if condition is false. The if condition is self.testArray == []. It's false because the array is not empty.

Perhaps you have reversed the sense of the condition without realizing it.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

Since your self.testArray is having items self.testArray == [] will be false. Also it will be much better to use self.testArray.count > 0 in case of check array items.

Arun Gupta
  • 2,628
  • 1
  • 20
  • 37