3

I like to change an array value for my function call.

Code for my ViewController2 that calls a function calculate

class ViewController2: UIViewController , UITableViewDelegate, UITableViewDataSource {

var springDisplacement : [Float] {return calculate(forceView2, stiffView2, springNumView2) }

}

Code for function calculate

public func calculateBoundary (f:[Float], s:[Float], n:NSInteger) -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) {

    println("\nForces in the array are")
    for rows in 0...n{
        if(rows==0||rows==n)
        { f[rows] = 0.0 }                
            println(f[rows])          
        }
}

I have an error: '@lValue $T5' is not identical to 'Float', when i want to change my f[rows] = 0.0

Any advices?

Terry Chia
  • 53
  • 1
  • 6

2 Answers2

4

This is because f parameter is an immutable array. You can change this to a mutable array parameter by using the function signature as follows

func calculateBoundary (var f:[Float], var s:[Float], n:NSInteger)  -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) { // }

If you want to also modify the original arrays passed to the function, you need to use inout parameters.

func calculateBoundary (inout f:[Float],inout s:[Float], n:NSInteger) -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) { // }

You can call it like this

var f : [Float] = [1.0,2.0]
var g : [Float] = [1.0,2.0]

let result = calculateBoundary(&f, &g, 1)
rakeshbs
  • 24,392
  • 7
  • 73
  • 63
1

f array is not mutable. You need to pass the f array as inout parameter:

 func calculateBoundary (inout f:[Float], s:[Float], n:NSInteger) -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) {...}

Then you can call calculateBoundary like this:

var springDisplacement : [Float] {return calculate(&forceView2, stiffView2, springNumView2) }
Jérôme
  • 8,016
  • 4
  • 29
  • 35
  • `var springDisplacement : [Float] {return calculate(&forceView2, stiffView2, springNumView2) }` gives me an error: 'inout [(Float)]' is not convertible to '[Float]'. I have declared my f and forceView2 to be array of type float. – Terry Chia Feb 12 '15 at 06:05