Reputation: 7426
I'm trying to create an extension to the ClosedRange
type, that would return nil
if the second parameter is lower than the first parameter.
I'm thinking to make something that could be used like this: myClosedRange = ClosedRange.safe(4,3)
I've created an extension like this:
extension ClosedRange {
static func safe(_ lhs: Int, _ rhs: Int) -> ClosedRange<Int>? {
guard lhs >= 0, rhs >= lhs else {
return nil
}
return lhs ... rhs
}
}
But when I try to use it like this: let myRange = ClosedRange.safe(4, 3)
, I'm getting the error: Generic parameter 'Bound' could not be inferred
I don't understand the error and don't know how to fix it? Any suggestion?
Upvotes: 0
Views: 147
Reputation: 285092
Specify the generic type
let myRange = ClosedRange<Int>.safe(4, 3)
or constrain the Range accordingly
extension ClosedRange where Bound : Comparable, Bound : ExpressibleByIntegerLiteral {
static func safe(_ lhs: Bound, _ rhs: Bound) -> ClosedRange<Bound>? {
guard lhs >= 0, rhs >= lhs else {
return nil
}
return lhs ... rhs
}
}
Upvotes: 1