In my quest to learn more about Swift, I'm looking at ways to improve my app and noticed a few places where I'm making assumptions where perhaps I shouldn't be.
When creating a new object, lets say a 'student', they need things like a name (String), age (Int) and score (Float). I read these from a JSON file, and put them into 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 as follows;
1. How should I modify my code to check that if a value is not a number, where it should be, the variable becomes just nil, or even better 0?
2. What if the key in the dictionary doesn't exist?
3. Are the different ways to do this, and if so, which is best practice?
Note that I want to keep this code as short as possible - if/else statements for each line are not what I'm looking for.
Thank you so much in advance!
NSJSONSerializationwill do some of the conversion for you. E.g. you should have{"name": "Bob", "age": 29, "score": 29042.3}.