Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeredpath/917ce10328fb34a0b7ba to your computer and use it in GitHub Desktop.
Save lukeredpath/917ce10328fb34a0b7ba to your computer and use it in GitHub Desktop.
A more generic approach to expectations
import Cocoa
protocol Matcher {
typealias Matchable
func matches(object: Matchable) -> Bool
}
class EqualMatcher<T:Equatable>: Matcher {
typealias Matchable = T
// this is a workaround for non-fixed class layout issues
let backingVar: T[]
var object: T {
get {
return backingVar[0]
}
set {
backingVar[0] = newValue
}
}
init(_ object: T) {
self.backingVar = [object]
}
func matches(otherObject: T) -> Bool {
return object == otherObject
}
}
class GreaterThanMatcher<T: Comparable>: Matcher {
typealias Matchable = T
// this is a workaround for non-fixed class layout issues
let backingVar: T[]
var object: T {
get {
return backingVar[0]
}
set {
backingVar[0] = newValue
}
}
init(_ object: T) {
self.backingVar = [object]
}
func matches(otherObject: T) -> Bool {
return otherObject > object
}
}
class Expectation<T> {
// this is a workaround for non-fixed class layout issues
let backingVar: T[]
var object: T {
get {
return backingVar[0]
}
set {
backingVar[0] = newValue
}
}
init(_ object: T) {
self.backingVar = [object]
}
func to<M: Matcher where M.Matchable == T>(matcher: M) -> Bool {
return matcher.matches(object)
}
func notTo<M: Matcher where M.Matchable == T>(matcher: M) -> Bool {
return !to(matcher)
}
}
func expect<T>(object: T) -> Expectation<T> {
return Expectation(object)
}
func equal<T:Comparable>(object: T) -> EqualMatcher<T> {
return EqualMatcher(object)
}
func beGreaterThan<T: Comparable>(object: T) -> GreaterThanMatcher<T> {
return GreaterThanMatcher(object)
}
expect(123).to(equal(123))
expect(123).notTo(equal(456))
expect(100).to(beGreaterThan(50))
@lukeredpath
Copy link
Author

I struggled to get the proxy/operator styles working with this so if anybody can figure out that would be great! You can see the proxy implementation here:

https://gist.github.com/lukeredpath/6af2f55f65faa52de74d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment