Skip to content

Instantly share code, notes, and snippets.

@lawrencelomax
Created September 5, 2014 11:30
Show Gist options
  • Save lawrencelomax/00ea2c00c9b6ca5bb4ab to your computer and use it in GitHub Desktop.
Save lawrencelomax/00ea2c00c9b6ca5bb4ab to your computer and use it in GitHub Desktop.
Return Early vs Nested Imperative Parsing in Swift
static func decodeImperative<X: XMLParsableType>(xml: X) -> Result<Animal> {
if let type = XMLParser.parseChildText("type")(xml: xml).toOptional() {
if let name = XMLParser.parseChildText("name")(xml: xml).toOptional() {
if let urlString = XMLParser.parseChildText("url")(xml: xml).toOptional() {
return Result.value(self(type: type, name: name, url: NSURL.URLWithString(urlString)) )
}
return Result.Error(decodeError("Could not parse 'urlString' as a String"))
}
return Result.Error(decodeError("Could not parse 'name' as a String"))
}
return Result.Error(decodeError("Could not parse 'type' as a String"))
}
static func decodeImperativeReturnEarly<X: XMLParsableType>(xml: X) -> Result<Animal> {
let maybeType = XMLParser.parseChildText("type")(xml: xml).toOptional()
let maybeName = XMLParser.parseChildText("name")(xml: xml).toOptional()
let maybeUrlString = XMLParser.parseChildText("url")(xml: xml).toOptional()
if maybeType == .None {
return Result.Error(decodeError("Could not parse 'type' as a String"))
}
if maybeName == .None {
return Result.Error(decodeError("Could not parse 'name' as a String"))
}
if maybeUrlString == .None {
return Result.Error(decodeError("Could not parse 'urlString' as a String"))
}
return Result.value(self(type: maybeType!, name: maybeName!, url: NSURL.URLWithString(maybeUrlString!)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment