Search code examples
iosswiftnsmutablearraynsarray

NSMutableArray and NSArray in swift


Initially I declared my array as:

var wrongAnswersArray: NSArray? = []
wrongAnswerLabel.isHidden = (wrongAnswersArray?.count)! <= 0 ? true:false

and my app worked fine. Later, I needed to modify the array so I declared it as mutable but I couldn't use the same statement for getting the count. XCode suggested to modified the statement in the following manner:

var wrongAnswersArray: NSMutableArray? = []
wrongAnswerLabel.isHidden = (wrongAnswersArray!).count <= 0 ? true:false

This compiles but fails at run time

1) Why couldn't we use the same statement? Why do NSArray and NSMutableArray behave differently?

2) Any way to solve this run time error?

Any documentation related to this would be helpful.


Solution

  • Use [String] like swift-array & make it let for constants & var for mutable(variable)

    var wrongAnswersArray: [String] = []
    wrongAnswerLabel.isHidden = (wrongAnswersArray.count) <= 0 ? true:false
    

    Further you can get help with https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html