0

I am using swiftlint as a way to code better, and for the most part I have been able to muddle my way through up to the following code which includes a forced downcast:

let questionToAdd = MultipleChoiceQuestion(question: dictionary["Question"] as! String,
            correctAnswer: dictionary["CorrectAnswer"] as! String,
            answers: dictionary["Answers"] as! [String])
           questions.append(questionToAdd)

I have been unable to remove the forced unwrapping. Any suggestions would be greatly appreciated. I have tried used the ELSE { return } but that isn't working either, could be the way I had it structured..nonetheless any help or point me in the right direction would be appreciated.

Douglas W. Palme
  • 390
  • 1
  • 4
  • 10
  • SwiftLint is a nitpicker. There is more than black and white. Force unwrapping is not evil per se. For example if the data is local (a property list or JSON file in the bundle) it cannot be modified and it's 100% safe to force unwrap the values. As mentioned in the answer the best way is to `decode` the data into `MultipleChoiceQuestion` directly. – vadian Feb 16 '20 at 06:02
  • Agreed Vadian. I am using a property list within the app it self. At some point we'll move it to firebase in which case its no longer an issue. – Douglas W. Palme Feb 17 '20 at 01:05

1 Answers1

1

The alternative to forced cast is an optional cast using as?. Typically you'd unwrap the results of those casts and then use the values, like this:

guard let question = dictionary["Question"] as? String, 
    let answer = dictionary["CorrectAnswer"] as? String,
    let answers = dictionary["Answers"] as? [String] else { return }

questions.append(MultipleChoiceQuestion(question: question, answer: answer, answers: answers))

However, since it looks like you're decoding something like JSON, a better choice would be to implement Decodable for your MultipleChoiceQuestion type do this transform for you.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37