I wanted to find some objects near another object in an array. I thought I could write an extension method like this, but I get this error:
// Error: Cannot invoke 'advanceBy' with an argument list of type '(Int)'
The Int
type is obviously wrong, but the indexOf
method takes a Self.Distance
argument and I'm not sure how to use that as a parameter type.
extension CollectionType where Generator.Element : Equatable {
func objectNear(object: Self.Generator.Element, indexModifier: Int) -> Self.Generator.Element? {
if let index = self.indexOf(object) {
let newIndex = index.advancedBy(indexModifier) // this doesn't work
//let newIndex = index.advancedBy(1) // but this this works
if self.indices.contains(newIndex) {
return self[newIndex]
}
}
return nil
}
}
(If there is a more Swifty approach I'd be happy to hear it, but I'd like to understand the above in any case.)