Last active
March 31, 2016 02:08
-
-
Save feighter09/5ac452c7b82d9edc92ebdeb8083583bf to your computer and use it in GitHub Desktop.
A Functional Approach to Optionals
This file contains 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
// Scenario: Parsing a JSON object that represents an item in a store | |
// JSON: { "name": "Bucket", "price": "19.95" } | |
// The following functions take in a price as a string, and output the result as an Int of cents | |
// cause I don't trust floating point operations when dealing with other people's money | |
struct Item { | |
let name: String | |
let price: Int | |
init(json: JSON) | |
{ | |
guard let name = json["name"].string, | |
price = parsePrice(json["price"].string) | |
else { return nil } | |
self.name = name | |
self.price = price | |
} | |
} | |
// If let approach | |
func parsePrice(price: String?) -> Int? | |
{ | |
if let price = price, | |
double = Double(price), | |
cents = Int(double * 100) { | |
return cents | |
} | |
return nil | |
} | |
// Guard let approach | |
func parsePrice(price: String?) -> Int? | |
{ | |
guard let price = price, | |
double = Double(price), | |
cents = Int(double * 100) | |
else { return nil } | |
return cents | |
} | |
// The functional approach | |
func parsePrice(price: String?) -> Int? | |
{ | |
return price.flatMap { price in Double(price) } | |
.map { double in Int(double * 100) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment