In my quest to learn more about Swift, I am looking for ways to improve my application and have noticed several places where I make assumptions, where maybe I shouldn't be.
When creating a new object, say, βstudent,β they need things like name ( String ), age ( Int ), and grade ( Float ). I read them from a JSON file and put them in an object like this:
// note, details is a [String:Any] type let name = details["name"] as! String let age = details["age"] as! Int let score = Float(details["score"]) self.student = Student(name: name, tutor_group: tutor_group, score: score)
So my questions are: 1. How can I change my code to verify that if the value is not a number, where it should be, the variable just becomes nil or even better than 0? 2. What if the key in the dictionary does not exist? 3. Are there different ways to do this, and if so, what is best?
Note that I want this code to be as short as possible - if / else for each line is not what I'm looking for.
Thank you so much in advance!
source share