andrewz
andrewz

Reputation: 5220

Swift 3 generic type function to clamp numeric values into 0 and 1 interval

I want to write a function that clamps a numeric value into the closed 0,1 interval:

func clamp01<T:???>(_ value:T) -> T {
  return value < 0 ? 0 : value > 1 ? 1 : value
}

In Swift 3 if I use T:Strideable I get a complaint that 0 and 1 must be typecast (0 as! T resolves the issue, but it's a forced cast).

In Swift 4 I may be able to use T:Numeric but I haven't tried that -- I am looking for a solution in Swift 3.

Upvotes: 1

Views: 378

Answers (1)

Martin R
Martin R

Reputation: 539965

You could define the function for all Comparable types which are also ExpressibleByIntegerLiteral, that covers all integer and floating point types:

func clamp01<T: Comparable & ExpressibleByIntegerLiteral>(_ value: T) -> T { 
    return value < 0 ? 0 : value > 1 ? 1 : value
}

Upvotes: 1

Related Questions