Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Created February 18, 2015 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danini-the-panini/0455aa9352378d87baae to your computer and use it in GitHub Desktop.
Save danini-the-panini/0455aa9352378d87baae to your computer and use it in GitHub Desktop.
String Calculator in Swift
import Foundation
class StringCalculator {
func add(string:String) -> Int {
let numbers = string.componentsSeparatedByString(",")
var total = 0
for number in numbers {
total += (number as NSString).integerValue
}
return total
}
}
var x = StringCalculator()
assert(x.add("1,2,3") == 6, "it handles lists of numbers.")
assert(x.add("1") == 1, "it handles single numbers.")
assert(x.add("") == 0, "it handles empty strings.")
assert(x.add("1,,2") == 3, "it handles empty strings between numbers.")
assert(x.add(",1,2,") == 3, "it handles empty strings on the ends.")
assert(x.add(" ") == 0, "it handles whitespace")
assert(x.add(" 1 ") == 1, "it handles whitespace around numbers")
assert(x.add(" 1, 2 ,3 ") == 6, "it handles whitespace around commas")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment