Let me start by saying what I have works...
let a:String
let b:Int
let c:Double
init?(doc:XMLDocument){
guard let tempString = (try? doc.objects(forXQuery: "path/path/A").first as? XMLNode)?.stringValue else {return nil}
self.a = tempString
guard let tempString2 = (try? doc.objects(forXQuery: "path/B").first as? XMLNode)?.stringValue else {return nil}
guard let tempInt = Int(tempString2) else {return nil}
self.b = tempInt
guard let tempString3 = (try? doc.objects(forXQuery: "path/path/C").first as? XMLNode)?.stringValue else {return nil}
guard let tempDouble = Double(tempString3) else {return nil}
self.c = tempDouble
}
}
I am not happy with it. I can simplify by doing null check and reusing a temporary variable
init?(doc:XMLDocument){
var tempString:String? = (try? doc.objects(forXQuery: "path/path/A").first as? XMLNode)?.stringValue
if tempString != nil {self.a = tempString!} else {return nil}
tempString = (try? doc.objects(forXQuery: "path/B").first as? XMLNode)?.stringValue
if tempString != nil && Int(tempString!) != nil {self.b = Int(tempString!)!} else {return nil}
tempString = (try? doc.objects(forXQuery: "path/path/C").first as? XMLNode)?.stringValue
if tempString != nil && Double(tempString!) != nil {self.c = Double(tempString!)!} else {return nil}
}
Ideally I want to be able to assign the properties as I check them without going through some sort of temporary variable.
something like:
struct Foo {
let a:String
let b:Int
let c:Double
init?(doc:XMLDocument){
do {
if case a = try (doc.objects(forXQuery: "path/path/A").first as? XMLNode)?.stringValue { } else {return nil}
if case b = Int(try (doc.objects(forXQuery: "path/path/B").first as? XMLNode)?.stringValue ?? "ZZZ") { } else {return nil}
if case c = Double(try (doc.objects(forXQuery: "path/path/C").first as? XMLNode)?.stringValue ?? "ZZZ") { } else {return nil}
} catch {
return nil
}
}
}
This errors with use of self without initializing all stored properties.
Is there a better way to do it?
I would suggest adding some helpful extensions to
XMLDocumentandXMLNodeas below,So, now your struct will look like this,