Search code examples
swiftdowncastswiftlint

Eliminating forced downcasts


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.


Solution

  • 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.