Created
February 18, 2015 08:18
-
-
Save danini-the-panini/0455aa9352378d87baae to your computer and use it in GitHub Desktop.
String Calculator in Swift
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
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