Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 'NSArray?' does not have member named 'count'

Tags:

ios

swift

I'm pretty sure .count returns the length of an array but for some reason when I used it, it threw a weird error.

Heres my code:

let dataFile = NSBundle.mainBundle().pathForResource(RopeDataFile, ofType: nil)
let ropes = NSArray(contentsOfFile: dataFile!);

for i in 0..<ropes.count {
}

RopeDataFile is a constant of a property list that I made earlier.

For some reason it gives this error on ropes.count,

'NSArray?' does not have member named 'count'.

I'm new to swift and sorry if the problem is really simple.

like image 885
user3143098 Avatar asked Apr 11 '26 23:04

user3143098


1 Answers

NSArray(contentsOfFile: dataFile!) returns an optional array. So you have to use like

ropes?.count

Or you can unwrap the ropes array first

if let array = ropes{
       for i in 0..< array.count {
       }

    }
like image 54
Anil Varghese Avatar answered Apr 13 '26 12:04

Anil Varghese