I'm trying to implement some classes which can be initialized with JSON data [String : AnyObject]
. Failable initializers appear to be perfect for this use case, but I can't seem to get the syntax correct (without creating ugly code).
Is it possible to do something like this?:
class Person {
let firstName: String
let middleName: String?
init?(JSONData data: [String : AnyObject]) {
do {
try {
self.firstName = data["firstName"] as! String
self.middleName = data["middleName"] as? String
}
} catch {
return nil
}
}
}
This is how I usually define model types with a failable initializer.
struct Person {
let firstName: String
let middleName: String?
init?(JSONData data:[String:AnyObject]) {
guard let firstName = data["firstName"] as? String else { return nil }
self.firstName = firstName
self.middleName = data["middleName"] as? String
}
}
As you can see I use a Struct instead of a Class, there are at least 2 big reasons for this:
failable initializers
work better with structs because you can return nil
without having initialized all the stored propertiesI also prefer using the guard let
construct because it makes clear that if some mandatory value is not retrieved then the initialisation must fail.
My version of the initializer do not require middleName
. I decided so because you defined middleName
as an optional. However if you want to make middleName
mandatory just change Person
as shown below
struct Person {
let firstName: String
let middleName: String
init?(JSONData data:[String:AnyObject]) {
guard let
firstName = data["firstName"] as? String,
middleName = data["middleName"] as? String else { return nil }
self.firstName = firstName
self.middleName = middleName
}
}
Nope!
[...] Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimisation.
The Swift Programming Language
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With