Created
January 2, 2017 01:58
-
-
Save patr1ck/866ace8847ff294262ef93d7094cd773 to your computer and use it in GitHub Desktop.
Ternary Swift 3 Operators Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
precedencegroup GreaterBPrecedence { | |
associativity: left | |
higherThan: LogicalConjunctionPrecedence | |
} | |
precedencegroup EqualBPrecedence { | |
associativity: left | |
higherThan: GreaterBPrecedence | |
} | |
infix operator >==: GreaterBPrecedence | |
infix operator <==>: EqualBPrecedence | |
typealias HashCashBitField = [UInt8] | |
func <==>(lhs: @autoclosure @escaping () -> HashCashBitField, rhs: @autoclosure @escaping () -> HashCashBitField) -> (Int) -> Bool { | |
return { (rangeIndexToMatchUpTo: Int) -> Bool in | |
let leftBitfield = lhs() | |
let rightBitfield = rhs() | |
var matchingRange = 0 | |
var counter = 0 | |
for leftByte in leftBitfield { | |
let rightByte = rightBitfield[counter] | |
let diff = leftByte ^ rightByte | |
var checker: UInt8 = 0b10000000 | |
while (checker & diff == 0) { | |
matchingRange = matchingRange + 1 | |
checker = checker >> 1 | |
} | |
counter = counter + 1 | |
} | |
return matchingRange >= rangeIndexToMatchUpTo | |
} | |
} | |
func >==(lhs: Int, rhs: (Int) -> Bool) -> Bool { | |
return rhs(lhs) | |
} | |
let field1: HashCashBitField = [0b01010101] | |
let field2: HashCashBitField = [0b01011111] | |
4 >== field1 <==> field2 | |
// => true | |
5 >== field1 <==> field2 | |
// => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment