Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

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

// 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)

I get an error on 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)

but then the getAverage was set to 4 instead of 4.5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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 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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...