Skip to content

Instantly share code, notes, and snippets.

@d-srd
Last active January 4, 2018 22:37
Show Gist options
  • Save d-srd/a12807290a7573a5cd315959ca5d274b to your computer and use it in GitHub Desktop.
Save d-srd/a12807290a7573a5cd315959ca5d274b to your computer and use it in GitHub Desktop.
A naive (?) solution to this problem: "Given an Array of Strings, return a String listing them with correct Oxford commas"
let test = [
[""],
["Hello"],
["Hello", "World"],
["cat", "apple", "mac", "dog", "mouse", "seahorse"]
]
let oxford: ([String]) -> String = { strings in
switch strings.count {
case 1: return strings[0]
case 1...: return strings.dropLast().joined(separator: ", ") + ", and " + strings.last!
default: return "no can do cap'n"
}
}
let output = test.map { oxford($0) }
// [""]
// ["Hello"]
// ["Hello, and World"]
// ["cat, apple, mac, dog, mouse, and seahorse"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment