Skip to content

Instantly share code, notes, and snippets.

@AaronGoldsmith
Created November 22, 2016 21:17
Show Gist options
  • Save AaronGoldsmith/b36f3335b3c76c8e6b248a8a82a80d2a to your computer and use it in GitHub Desktop.
Save AaronGoldsmith/b36f3335b3c76c8e6b248a8a82a80d2a to your computer and use it in GitHub Desktop.
// Aaron Goldsmith
// Gate Structure
import UIKit
struct Gate{
private let logic: Logic // Holds the Logical Gate
private var pinA: Bool?
private var pinB: Bool?
// Enumeration for Logic switch
enum Logic{
case AND, OR, NOT
}
// Returns new Gate
func setBoth(_ pinA:Bool? , _ pinB: Bool?) -> Gate{
var generated:Gate = Gate(withLogic: self.logic)
generated.settingBoth(pinA, pinB)
return generated
}
// mutates current gate
mutating func settingBoth(_ pinA:Bool? , _ pinB: Bool?){
self.pinA = pinA;
self.pinB = pinB;
}
// Evaluation of logic
private func checkLogic(_ logic: Logic) -> Bool{
switch logic{
case .AND: return (pinA! && pinB!)
case .OR: return (pinA! || pinB!)
case .NOT: return !(pinA!)
}
}
// returns optional Bool
var evaluate:Bool? {
guard pinB != nil else{
return (self.logic != .NOT) ? nil : !(pinA!)}
return checkLogic(self.logic)
}
// Normal initialization
init(withLogic gate: Logic){
self.logic = gate;
settingBoth(nil, nil)
}
// special initialization
init(_ ar: Bool?, _ br: Bool?, _ cr: Logic) {
self.init(withLogic: cr)
self.settingBoth(ar, br)
}
}
// Gate Delegate
protocol GateDelegate{
func LinkGates(_: inout Gate,_: inout Gate,usingLogic: Gate.Logic) -> Gate
func addGates(gate: Gate...)
var gates: Array<Gate> { get set }
}
extension GateDelegate{
func LinkGates(_ g1 : inout Gate, _ g2: inout Gate, usingLogic: Gate.Logic) -> Gate{
return Gate(g1.evaluate,g2.evaluate,usingLogic)
}
}
// Class for Delegate
class Board: GateDelegate{
internal var gates: Array<Gate> = []
func addGates(gate: Gate...) {
for gates in gate{
self.gates.append(gates)
}
}
}
// TESTING
let circuitBoard = Board()
circuitBoard.addGates(gate:
Gate.init(withLogic: .AND).setBoth(true,true),
Gate.init(withLogic: .OR).setBoth(false, true),
Gate.init(withLogic: .OR).setBoth(false, true),
Gate.init(withLogic: .NOT).setBoth(false, nil))
var gates = circuitBoard.gates
var x = circuitBoard.LinkGates(&gates[0], &gates[1], usingLogic: .AND)
var y = circuitBoard.LinkGates(&x, &gates[1], usingLogic: .OR)
let z = Gate.init(withLogic: .NOT).setBoth(gates[0].evaluate, nil).evaluate
// creates a new gate using a NOT gate on gate1
// (not)( true AND true ) = false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment