Created
September 5, 2014 11:30
-
-
Save lawrencelomax/00ea2c00c9b6ca5bb4ab to your computer and use it in GitHub Desktop.
Return Early vs Nested Imperative Parsing in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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