I ran into some interesting behaviour the other day. Basically I originally wrote a helper function to prevent errors while automatically typecasting a JSON property. It looked like this:
func readData<T>(inout output:T, _ input:AnyObject?, _ throwError:Bool = true) throws
{
if (input == nil) {
if (throwError) {
throw ConvertError.MissingParameter
}
}
else {
if let inputObject:T = input as? T {
output = inputObject
}
else if (throwError) {
throw ConvertError.WrongType
}
}
}
var myProperty:String
try readData(&myProperty, myJson["data"], true)
This checks the property exists, and that it's the right type. If all goes well, the value inside myProperty changes.
A little while later, I needed to make some changes. I made a class called properties and it has a list of properties inside of it. There are 2 variables of this type of class: originalProperties and modifiedProperties Each of the properties inside these classes are optional variables now, specifically to keep track of what properties the user has changed. Basically it looks like this:
class Properties
{
var x:Int?
var y:Int?
}
Now when I run this:
try readData(&originalProperties.x, myJson["x"], false)
It doesn't work anymore. I looked at another question and it explained what was happening. Basically while x still had a value of nil (because it's an optional), I was passing a nil value into my readData function, so the Template type isn't set properly and that's why it fails on the input as? T code.
fortunately, I don't have to have such a creative function anymore. I can just use this:
originalProperties.x= obj["x"] as? Int
But then I'll lose my thrown error functionality if I needed it.
Does anyone have any ideas how I can make sure my Template type gets passed correctly while it still has a value of nil? I even read in another thread that I might have to use some sort of default value closure, but it would be interesting to see if there's a way to work around this.