-
-
Save vittoriom/90e48645b984b381210a70b68b25dead to your computer and use it in GitHub Desktop.
reports func must be more Swifty.
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
enum State { | |
case Happy | |
case Sad | |
} | |
struct Day { | |
let name: String | |
let state: State | |
} | |
struct Month { | |
let name: String | |
let days: [Day] | |
} | |
func swiftyReports(months: [Month]) -> (happy: Int, sad: Int, total: Int) { | |
let flat = months | |
.flatMap { $0.days } | |
.map { $0.state } | |
let sad = flat.filter { $0 == .Sad }.count | |
let happy = flat.filter { $0 == .Happy }.count | |
// happy + sad can be rewritten as `flat.count` | |
return (happy, sad, happy + sad) | |
} | |
let months = [Month(name: "Month 1", days: [ | |
Day(name: "Day 1", state: .Happy), | |
Day(name: "Day 2", state: .Happy), | |
Day(name: "Day 3", state: .Sad)]), | |
Month(name: "Month 2", days: [ | |
Day(name: "Day 1", state: .Happy), | |
Day(name: "Day 2", state: .Sad), | |
Day(name: "Day 3", state: .Happy), | |
Day(name: "Day 4", state: .Happy)])] | |
let report = swiftyReports(months) | |
print("\(report.happy) happy days, \(report.sad) sad days, \(report.total) total") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment