【问题标题】:Swift - Error calling a function from another function [duplicate]Swift - 从另一个函数调用函数时出错[重复]
【发布时间】:2014-06-08 07:08:13
【问题描述】:

在关注 Apple 的书 "The Swift Programming Language"

我在处理“实验 - 编写一个计算其参数平均值的函数”时遇到了一个问题。从第一章开始。

要确定一组数字的平均值,我想重用我的数字总和 [setOf(numbers: Int...)] 函数并除以数字计数 [numbers.count]。我收到错误:

Could not find an overload for '__conversions' that accepts the supplied arguments  

当我尝试从我的 averageOf(numbers) 函数调用 sumOf(numbers) 时。

我应该改变什么才能从我的averageOf(numbers) 函数正确调用我的sumOf(numbers) 函数?

func sumOf(numbers: Int...) -> Int {
    var sum = 0 //0
    for number in numbers {
        sum += number
    }
    return sum  //651
}
sumOf(42, 597, 12)  //651

func averageOf(numbers: Int...) -> Int {
    var sum = sumOf(numbers) //Issue in this line
    return  sum / numbers.count
}
averageOf(42, 597, 12)

将上面的代码粘贴到新的 Xcode 6 Playground 中以重新创建。

Error Screenshot(我需要 10 个声望点才能发布图片。)

【问题讨论】:

标签: ios swift


【解决方案1】:

您传递的类型与函数所期望的不同。显然Int...Int[] 不一样。

您可以创建一个接受 Int[] 并返回总和的覆盖。

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多