大佬教程收集整理的这篇文章主要介绍了数组 – 如何使用可变参数转发函数?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
问题出现了,因为我试图调用一个函数,该函数在一个带有可变数量参数的函数中接受可变数量的参数。
// Function 1 func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } // Example Usage sumOf(2,5,1) // Function 2 func averageOf(numbers: Int...) -> Int { return sumOf(numbers) / numbers.count }@H_801_18@这个平均的实现对我来说似乎是合理的,但它不能编译。当您尝试调用sumOf(数字)时,它会出现以下错误:
Could not find an overload for '__converstion' that accepts the supplied arguments@H_801_18@在averageOf内,数字的类型为Int []。我相信sumOf期待一个元组而不是一个数组。
因此,在Swift中,如何将数组转换为元组?
但是,您可以通过提供重载来解决您的问题:
// This function does the actual work func sumOf(_ numbers: [Int]) -> Int { return numbers.reduce(0,+) // functional style with reduce } // This overload allows the varia@R_197_11622@ notation and // forWARDs its args to the function above func sumOf(_ numbers: Int...) -> Int { return sumOf(numbers) } sumOf(2,1) func averageOf(_ numbers: Int...) -> Int { // This calls the first function directly return sumOf(numbers) / numbers.count } averageOf(2,1)@H_801_18@也许有更好的方法(例如,Scala使用特殊类型的ascription来避免需要重载;你可以在averageOf中写入Scala sumOf(数字:_ *)而不定义两个函数),但我还没有找到它文档。
以上是大佬教程为你收集整理的数组 – 如何使用可变参数转发函数?全部内容,希望文章能够帮你解决数组 – 如何使用可变参数转发函数?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。