Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Created February 18, 2015 08:18
Show Gist options
  • 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.

Revisions

  1. Daniel Smith created this gist Feb 18, 2015.
    25 changes: 25 additions & 0 deletions StringCalculator.playground
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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")