Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update binary to return Optionals #68

Merged
merged 1 commit into from
Sep 16, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions binary/BinaryExample.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,26 @@ struct Binary {

var toDecimal:Int {get {return Int(UIntValue)}}

private func bi2Uint(input:String) -> UInt{
private func bi2Uint(input:String) -> UInt?{
let orderedInput = Array(input.characters.reverse())
var tempUInt:UInt = 0
for (inx,each) in orderedInput.enumerate(){
if each == "1" {
tempUInt += UInt(0x1 << inx)
}
if (each != "0" && each != "1") {
return 0
return nil
}
}
return tempUInt
}

init(_ input:String){
self.UIntValue = bi2Uint(input)
init?(_ input:String){
if bi2Uint(input) != nil {
self.UIntValue = bi2Uint(input)!
} else {
return nil
}

}
}
30 changes: 22 additions & 8 deletions binary/BinaryTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,51 @@ import XCTest

class BinaryTests: XCTestCase {

func testBinary0IsDecimal0() {
XCTAssertEqual( 0, Binary("0")?.toDecimal)
}

func testBinary1isDecimal1() {
XCTAssertEqual( 1, Binary("1").toDecimal)
XCTAssertEqual( 1, Binary("1")?.toDecimal)
}

func testBinary10isDecimal2() {
XCTAssertEqual( 2, Binary("10").toDecimal)
XCTAssertEqual( 2, Binary("10")?.toDecimal)
}

func testBinary11isDecimal3() {
XCTAssertEqual( 3, Binary("11").toDecimal)
XCTAssertEqual( 3, Binary("11")?.toDecimal)
}

func testBinary100isDecimal4() {
XCTAssertEqual( 4, Binary("100").toDecimal)
XCTAssertEqual( 4, Binary("100")?.toDecimal)
}

func testBinary1001isDecimal9() {
XCTAssertEqual( 9, Binary("1001").toDecimal)
XCTAssertEqual( 9, Binary("1001")?.toDecimal)
}

func testBinary11010isDecimal26() {
XCTAssertEqual( 26, Binary("11010").toDecimal)
XCTAssertEqual( 26, Binary("11010")?.toDecimal)
}

func testBinary10001101000isDecimal1128() {
XCTAssertEqual( 1128, Binary("10001101000").toDecimal)
XCTAssertEqual( 1128, Binary("10001101000")?.toDecimal)
}

func testBinaryIgnoresLeadingZeros() {
XCTAssertEqual( 31, Binary("000011111")?.toDecimal)
}

func testInvalidBinaryIsDecimal0() {
XCTAssertEqual( 0, Binary("carrot123").toDecimal)
XCTAssertNil ( Binary("carrot123")?.toDecimal)
}

func testInvalidBinaryNumbers() {
XCTAssertNil ( Binary("012")?.toDecimal)
XCTAssertNil ( Binary("10nope")?.toDecimal)
XCTAssertNil ( Binary("nope10")?.toDecimal)

}

}