1

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!! It made the entire code simpler. Earlier I was using '?' everywhere. I am new to swift. I will follow the documentation you sent.
This answer is not so "Swifty", and is unnecessarily verbose. You should use my "Swiftier" and more reactive answer: stackoverflow.com/a/44694853/1311272
A couple of notes: ternaries containing ? true : false do not need to exist (just use the condition instead), and why would the array have fewer than zero elements (use wrongAnswersArray.isEmpty or similar instead)?
1

Why hassel with array.count <= 0 ? true : false? And why <= even? Can an array have a negative length? You should just do this instead:

// start empty
var wrongAnswers = [String]()
... // app might append wrong answers to the array

// Later check:
wrongAnswersLabel.isHidden = wrongAnswers.isEmpty // done!

Even better:
Or you could "react" to changes to the array, by using Swift "property observer", e.g. "willSet":

// start empty
var wrongAnswers: [String] = [] {
    willSet {
        // Using `willSet` instead of `didSet` allows for use of implicitly declared variable `newValue`
        // which is good since it makes refactoring simpler, not having to refer to the name
        // of this variable (`wrongAnswers`) which we might want to change in the future
        wrongAnswersLabel.isHidden = newValue.isEmpty
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.