I'm using xcode 16.1 withSwiftUI. 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] { some code } 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 even though it's not empty on the sending side. Please help. Thank you.
arrays
This function you have is set up to receive an array of Double
s and let you refer to them as costa
:
func myfunc(costa: [Double]) {
// some code
}
If you're calling the function like this:
myfunc(costa: [])
then you're passing in an empty array. []
means an empty array.
If you want to pass in some values, you need them in the array, e.g.:
myfunc(costa: [1.0, 2.1, 3.2, 4.3])
If you need to return an array of Double
s - or anything - you would use a function like this:
func myfunc(costa: [Double]) -> [Double] {
// some code
return myArray // which would be an array of Doubles
}
A very useful feature of Swift is the ability to hide the name of the variable, so you don't have to enter it every time. Just put an underscore before the first variable name in the function's signature, i.e.:
func myfunc(_ costa: [Double]) {
// some code
}
This lets you access the array of Double
s in costa
. To call it you would use:
myfunc([1.0, 2.1, 3.2, 4.3])
A similar helpful feature is replacing the underscore with something else that makes sense when you read the function out loud. Consider this:
func addFive(_ value: Int) -> Int {
return value + 5
}
You call it with:
let total: Int = addFive(6) // 11
You can change the signature to something that makes more sense when read out loud:
func addFive(to value: Int) -> Int {
return value + 5
}
You call it with:
let total: Int = addFive(to: 6) // 11
Hope this helps.
Also, just an FYI, you're writing in Swift when you do things like this. SwiftUI is for user interface stuff like Buttons, Text, Views, etc.
Thanks. What if I don't know what's in the array?