0

Note: there are a few other questions about "Generic parameter 'T' could not be inferred" - for example this one Generic parameter 'T' could not be inferred - but none of them are related to Range limits.

Consider this code:

 (0..<10).map{ }

Why is this causing the aforementioned error?

enter image description here

Does the compiler want some "help" on determining the types ? If so what is the syntax?

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Closure types are only automatically inferred for *single expression closures,” compare e.g. https://stackoverflow.com/q/42534207/1187415 – Martin R May 15 '20 at 11:25
  • 1
    @MartinR I was just about to share the same exact question! What a coincidence! – Sweeper May 15 '20 at 11:26
  • A simple example: `let foo = (0..<10).map { Float($0) }` compiles, but `let bar = (0..<10).map { let out = Float($0); return out }` does not. – Martin R May 15 '20 at 11:28
  • `var sineWave = (0..<10).map { y -> Float in let out = sin(2.0 * Float.pi * Float(y)) return out }` – udbhateja May 15 '20 at 11:35
  • 1
    @udbhateja Thanks for that help on the syntax: please feel free to add an answer and i'll upvote – WestCoastProjects May 15 '20 at 11:40

2 Answers2

2

Given the comments from @MartinR and @Sweeper it is easy enough to understand and fix the problem once it was made clear *where* the error actually lies . Xcode has highlighted the wrong place (see OP).

let sineWave: [Float] = (0..<10).map {
            let out: Float = amplitude * sin(2.0 * .pi * Float($0) / Float(sampleFreq))
            return out
    }

Note that the problem is on the return type of the overall closure not on the Range(0..<10) .

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Unrelated to your question, but does `sinewave` really need to be mutable? Unless you mutate it later on, it should be immutable. – Dávid Pásztor May 15 '20 at 11:43
  • Sure it was originally a `let` - and should be reverted to same. i was trying all sorts of things to figure out what were happening here ;) . Just fixed it back now. – WestCoastProjects May 15 '20 at 11:44
  • @javadba you don't even need to set the resulting type explicitly as long as you have a single expression `let sineWave = (0..<10).map { amplitude * sin(2.0 * .pi * Float($0) / Float(sampleFreq)) }` – Leo Dabus May 15 '20 at 14:58
1

The construct

   y -> Float in

can be used to provide the necessary hints to the compiler:

    var sineWave = (0..<10).map { y -> Float in
        let out = amplitude * sin(2.0 * .pi * Float(y) / Float(sampleFreq))
        return out
    }
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
udbhateja
  • 948
  • 6
  • 21