Skip to content

Commit

Permalink
Added boolean XOR.
Browse files Browse the repository at this point in the history
  • Loading branch information
benfed committed Dec 10, 2018
1 parent f5d8258 commit 1811e83
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
9 changes: 9 additions & 0 deletions BXSwiftUtils/Math & Geometry/Bool+Operators.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import Foundation

infix operator ||= : AssignmentPrecedence
infix operator &&= : AssignmentPrecedence
infix operator ^^ : LogicalDisjunctionPrecedence

extension Bool
{
/// OR and assign
public static func ||= (lhs: inout Bool, rhs: @autoclosure () throws -> Bool) rethrows
{
if (!lhs)
Expand All @@ -21,11 +23,18 @@ extension Bool
}
}

// AND and assign
public static func &&= (lhs: inout Bool, rhs: @autoclosure () throws -> Bool) rethrows
{
if (lhs)
{
lhs = try rhs()
}
}

// XOR
public static func ^^ (lhs: Bool, rhs: Bool) -> Bool
{
return (lhs && !rhs) || (!lhs && rhs)
}
}
46 changes: 46 additions & 0 deletions BXSwiftUtilsTests/Math & Geometry/Bool+OperatorsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,50 @@ class Bool_OperatorsTests : XCTestCase
boolValue &&= false
XCTAssertFalse(boolValue) // 1 0 | 0
}

func testXOR()
{
var boolValue: Bool = false

boolValue = false ^^ false
XCTAssertFalse(boolValue) // 0 0 | 0

boolValue = false ^^ true
XCTAssertTrue(boolValue) // 0 1 | 1

boolValue = true ^^ false
XCTAssertTrue(boolValue) // 1 0 | 1

boolValue = true ^^ true
XCTAssertFalse(boolValue) // 1 1 | 0
}

func testXORPrecedenceLeftToRight() // same as right to left
{
var boolValue: Bool = false

boolValue = false ^^ false ^^ true
XCTAssertTrue(boolValue)

boolValue = false ^^ false ^^ false
XCTAssertFalse(boolValue)

boolValue = false ^^ true ^^ true
XCTAssertFalse(boolValue)

boolValue = false ^^ true ^^ false
XCTAssertTrue(boolValue)

boolValue = true ^^ false ^^ true
XCTAssertFalse(boolValue)

boolValue = true ^^ false ^^ false
XCTAssertTrue(boolValue)

boolValue = true ^^ true ^^ false
XCTAssertFalse(boolValue)

boolValue = true ^^ true ^^ true
XCTAssertTrue(boolValue)
}
}

0 comments on commit 1811e83

Please sign in to comment.