I'm new to Swift, and just start to learn this language by following The Swift Programming Language. In this book, there is an exercise question that ask me to write a function to calculate the average of an array. Here is my code:
我是Swift的新手,只是按照Swift编程语言开始学习这门语言。在本书中,有一个练习题,要求我编写一个函数来计算数组的平均值。这是我的代码:
func avgArray(elements: Int...)->Double{
var avg:Double = 0
var sum = 0
var count = 0
for element in elements {
sum += element
count += 1
}
avg = Double(sum) / Double(count)
return avg
}
let numberlist = [2,3,6,7,2,7,0,9,12]
let average = avgArray(numberlist)
I don't know why I can't pass the array into my function. Also, is there a way besides using a count variable to keep track of the number of elements in the array?
我不知道为什么我不能将数组传递给我的函数。另外,除了使用count变量来跟踪数组中的元素数量之外,还有其他方法吗?
1 个解决方案
#1
0
I don't know why I can't pass the array into my function.
我不知道为什么我不能将数组传递给我的函数。
Your elements
is not an array, it is a variadic parameter. Change it to
您的元素不是数组,它是一个可变参数。将其更改为
func avgArray(elements: [Int])->Double{
and you should be good to go.
你应该好好去。
is there a way besides using a count variable to keep track of the number of elements in the array?
有没有办法除了使用count变量来跟踪数组中的元素数量?
Absolutely. count
property of the array itself. You can use it in your code like this:
绝对。 count数组本身的属性。您可以在代码中使用它,如下所示:
avg = Double(sum) / Double(elements.count)
#1
0
I don't know why I can't pass the array into my function.
我不知道为什么我不能将数组传递给我的函数。
Your elements
is not an array, it is a variadic parameter. Change it to
您的元素不是数组,它是一个可变参数。将其更改为
func avgArray(elements: [Int])->Double{
and you should be good to go.
你应该好好去。
is there a way besides using a count variable to keep track of the number of elements in the array?
有没有办法除了使用count变量来跟踪数组中的元素数量?
Absolutely. count
property of the array itself. You can use it in your code like this:
绝对。 count数组本身的属性。您可以在代码中使用它,如下所示:
avg = Double(sum) / Double(elements.count)