From 1811e8376211c6b52c89c73d8ce3af3389e1a970 Mon Sep 17 00:00:00 2001 From: Benjamin Federer Date: Mon, 10 Dec 2018 16:28:24 +0100 Subject: [PATCH] Added boolean XOR. --- .../Math & Geometry/Bool+Operators.swift | 9 ++++ .../Math & Geometry/Bool+OperatorsTests.swift | 46 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/BXSwiftUtils/Math & Geometry/Bool+Operators.swift b/BXSwiftUtils/Math & Geometry/Bool+Operators.swift index 39c5cc1..7eeb5f5 100644 --- a/BXSwiftUtils/Math & Geometry/Bool+Operators.swift +++ b/BXSwiftUtils/Math & Geometry/Bool+Operators.swift @@ -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) @@ -21,6 +23,7 @@ extension Bool } } + // AND and assign public static func &&= (lhs: inout Bool, rhs: @autoclosure () throws -> Bool) rethrows { if (lhs) @@ -28,4 +31,10 @@ extension Bool lhs = try rhs() } } + + // XOR + public static func ^^ (lhs: Bool, rhs: Bool) -> Bool + { + return (lhs && !rhs) || (!lhs && rhs) + } } diff --git a/BXSwiftUtilsTests/Math & Geometry/Bool+OperatorsTests.swift b/BXSwiftUtilsTests/Math & Geometry/Bool+OperatorsTests.swift index f62488c..9d4659b 100644 --- a/BXSwiftUtilsTests/Math & Geometry/Bool+OperatorsTests.swift +++ b/BXSwiftUtilsTests/Math & Geometry/Bool+OperatorsTests.swift @@ -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) + } }