找不到接受所提供参数的“/"重载 [英] Could not find an overload for '/' that accepts the supplied arguments

查看:26
本文介绍了找不到接受所提供参数的“/"重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Playground - noun: a place where people can play


func getAverage(numbers: Int...) -> Double{
    var total = 0
    var average:Double = 0

    for number in numbers{
        total = total + number
    }

    average = total / numbers.count

    return average
}

getAverage(3, 6)

我在 average = total/numbers.count

找不到接受所提供参数的/"重载

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

我尝试通过以下方式修复:

I tried to fix by doing:

average = Double(total/numbers.count)

但随后将 getAverage 设置为 4 而不是 4.5

but then the getAverage was set to 4 instead of 4.5

推荐答案

Swift 中没有这种隐式转换,所以你必须自己显式转换:

There are no such implicit conversions in Swift, so you'll have to explicitly convert that yourself:

average = Double(total) / Double(numbers.count)

来自 Swift 编程语言:值永远不会隐式转换为另一种类型."(部分:Swift 之旅)

From The Swift Programming Language: "Values are never implicitly converted to another type." (Section: A Swift Tour)

但是您现在使用的是 Swift,而不是 Objective-C,因此请尝试以更面向功能的方式进行思考.你的函数可以这样写:

But you're now using Swift, not Objective-C, so try to think in a more functional oriented way. Your function can be written like this:

func getAverage(numbers: Int...) -> Double {
    let total = numbers.reduce(0, combine: {$0 + $1})
    return Double(total) / Double(numbers.count)
}

reduce 将第一个参数作为累加器变量的初始值,然后将 combine 函数应用于累加器变量和数组中的每个元素.在这里,我们传递一个匿名函数,该函数使用 $0$1 来表示它传递的第一个和第二个参数并将它们相加.

reduce takes a first parameter as an initial value for an accumulator variable, then applies the combine function to the accumulator variable and each element in the array. Here, we pass an anonymous function that uses $0 and $1 to denote the first and second parameters it gets passed and adds them up.

更简洁,你可以这样写:numbers.reduce(0, +).

Even more concisely, you can write this: numbers.reduce(0, +).

请注意类型推断如何出色地仍然发现 totalInt.

Note how type inference does a nice job of still finding out that total is an Int.

这篇关于找不到接受所提供参数的“/"重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆