0

I'm trying to write some generic numerical code in Swift. Here's an example:

func linstep<X>(lambda: X, a: X, b: X) -> X {
    return (X(1)-lambda)*a+lambda*b
}

That results in 'X' cannot be constructed because it has no accessible initializers. I need to ensure that 1 can be converted to X.

So I tried this variant:

func linstep<X: IntegerLiteralConvertible>(lambda: X, a: X, b: X) -> X {
    return (X(integerLiteral: 1)-lambda)*a+lambda*b
}

But that failed also.

How should I write my function?

(I know linear interpolation can be algebraically rearranged to eliminate the use of 1. But that's not the point of my question.)

sigfpe
  • 7,996
  • 2
  • 27
  • 48
  • 1
    This might be what you are looking for: [What protocol should be adopted by a Type for a generic function to take any number type as an argument in Swift?](http://stackoverflow.com/questions/25575513/what-protocol-should-be-adopted-by-a-type-for-a-generic-function-to-take-any-num). – Martin R Oct 14 '15 at 17:02
  • @MartinR That's exactly what I'm looking for. (And exactly what I was hoping the answer wouldn't be :-) – sigfpe Oct 14 '15 at 17:30
  • 1
    For *integer* types it would be sufficient to require conformance to `IntegerArithmeticType`. But I assume that you want to do floating point numerics, and there is (as far as I know) no corresponding protocol. `FloatingPointType` does not help. – Martin R Oct 14 '15 at 17:36
  • What's needed is a Swift version of Haskell's Num type class. It's pretty straightforward to write but it's one of those things that's probably better shared by everyone rather than having everyone implement their own. – sigfpe Oct 14 '15 at 17:40

0 Answers0