array

I'm using xcode 16.1 withSwift. I want to know how to call a function passing in an array. Also I need to know how to declare the function receiving the array. I currently have:

func myfunc(costa: [Double]) {
}

I call it like this:

myfunc(costa:[ ])

It's an array of Doubles. I don't get any errors but the array is always empty. Please help. Thank you.

I'm not sure to understand.

With the present code:

func myfunc(costa: [Double]) {
}

myfunc(costa:[ ])

calling with [] parameter of course uses an empty array.

If you call

func myfunc(costa: [Double]) {
  print(costa.count)
}

myfunc(costa:[ 10.0, 20.0])

It will not be empty. You will see in log it has 2 items.

But is it what you want ?

What do you do in myfunc ? Just use the array (as in the example above) ? Or add items to the array ?

Yes that works. But what if I don't know what's going to be in the array? It's for a pizza delivery program. The array holds the cost of the deliveries. In myfunc I want to print each element out to the screen. Thanks for your help.

So, you will pass the array populated with the prices (in fact, you probably need to pass more information, to know to which pizza or customer a price refers to).

Is it for SwiftUI or UIKit ?

for SwiftUI, you would have a State var with the costs (or more info) and could use List to display

@State var costs: [Double] = [] // You will have to append this array when you add a pizza

In the body of the View, something like:

struct ContentView: View {
    @State var costs: [Double] = []  // You will have to append this array when you add a pizza
    @State var newCost: Double = 0
    
    var body: some View {
        VStack {

            List(costs, id: \.self) { cost in
                Text("cost: \(String(format: "%4.2f", cost) )")
            }

            HStack {
                Text("New pizza cost")
                TextField("", value: $newCost, format: .number)
                    .border(.blue)
            }

            Button(action: {
                if newCost > 0 { self.costs.append(newCost) }
                newCost = 0
            }) {
                Text("Append")
            }
            Spacer()
        }
    }
}
array
 
 
Q