Harper Creek
Harper Creek

Reputation: 437

Can't convert [Double] to Double within function

How do I make this run without getting this error?

Cannot invoke 'stride' with an argument list of type '(from: Double, to: [Double], by: Double)'

I know the answer is right there but I'm new to coding and am having trouble making that [double] just a double within the func.

var array = [50.0, 40.0, 60.0]
var newArray = [Float]()

func possible(variable: [Double]) -> Float {
    var chance: Double = 0.0
    let last = variable
    let interval = -10.0
    for _ in stride(from: 100.0, to: last, by: interval) {
        chance += 0.05
    }
    return Float(chance)
}

newArray.append(possible(variable: array))

I get why it doesn't work, because I'm telling last to be an array. But how do I make it run each component of array individually. I thought doing let last = (variable[index]) would work but it did not.

Ideally the end result would be newArray = [0.25, 0.3, 0.2]

Upvotes: 0

Views: 639

Answers (1)

rmaddy
rmaddy

Reputation: 318794

You need your variable parameter to be a single Double, not an array. Then you need to call possible once for each value in array.

Here's one way to update your code:

var array = [50.0, 40.0, 60.0]

func possible(variable: Double) -> Float {
    var chance: Double = 0.0
    let interval = -10.0
    for _ in stride(from: 100.0, to: variable, by: interval) {
        chance += 0.05
    }
    return Float(chance)
}

let newArray = array.map { possible(variable: $0) }
print(newArray)

But here's an simpler implementation of possible:

func possible(variable: Double) -> Float {
    return Float((100 - variable) / 10 * 0.05)
}

Your entire set of code can be reduced to:

var array = [50.0, 40.0, 60.0]
let newArray = array.map { Float((100 - $0) / 10 * 0.05) }

Upvotes: 2

Related Questions