Last active
February 19, 2017 12:25
-
-
Save torinkwok/799784dc28fd85e4751b935696030a1d to your computer and use it in GitHub Desktop.
Handy Operators
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 | |
// MAKR: =~ | |
protocol RegularExpressionMatchable { | |
func match( pattern: String, options: NSRegularExpression.Options ) throws -> Bool | |
} | |
extension String: RegularExpressionMatchable { | |
/// Conformance to <RegularExpressionMatchable> protocol | |
func match( pattern: String, options: NSRegularExpression.Options = [] ) throws -> Bool { | |
let regex = try NSRegularExpression( pattern: pattern, options: options ) | |
return regex.numberOfMatches( | |
in: self | |
, options: [] | |
, range: NSRange( location: 0, length: 0.distance( to: utf16.count ) ) | |
) != 0 | |
} | |
} | |
infix operator =~: MultiplicationPrecedence | |
func =~<T: RegularExpressionMatchable> ( lhs: T, rhs: String ) -> Bool { | |
return try! lhs.match( pattern: rhs, options: [] ) | |
} | |
// MARK: ± | |
infix operator ±: AdditionPrecedence | |
func ± ( lhs: Double, rhs: Double ) -> ( Double, Double ) { | |
return ( lhs + rhs, lhs - rhs ) | |
} | |
prefix operator ± | |
prefix func ± ( value: Double ) -> ( Double, Double ) { | |
return 0 ± value | |
} | |
// MARK: /% | |
fileprivate func _divmod<T: Integer> | |
( dividing left: T, by right: T ) -> ( T, T ) { | |
return ( ( left / right ), ( left % right ) ) | |
} | |
fileprivate func _divmod<T: BinaryFloatingPoint> | |
( dividing left: T, by right: T ) -> ( T, T ) { | |
return | |
( ( left / right ).rounded( .towardZero ) | |
, ( left / right ).truncatingRemainder( dividingBy: right ) ) | |
} | |
infix operator /%: MultiplicationPrecedence | |
public func /%<T: Integer> ( left: T, right: T ) -> ( T, T ) { | |
return _divmod( dividing: left, by: right ) | |
} | |
public func /%<T: BinaryFloatingPoint> ( left: T, right: T ) -> ( T, T ) { | |
return _divmod( dividing: left, by: right ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment