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
232 views
in Technique[技术] by (71.8m points)

Why can't I divide integers in swift?

In the Swift "Tour" documentation, there's an exercise where you build on the following function to average a set of numbers:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}

I can make this work using something like the following:

func averageOf(numbers: Double...) -> Double {
    var sum: Double = 0, countOfNumbers: Double = 0
    for number in numbers {
        sum += number
        countOfNumbers++
    }
    var result: Double = sum / countOfNumbers
    return result
}

My question is, why do I have to cast everything as a Double to make it work? If I try to work with integers, like so:

func averageOf(numbers: Int...) -> Double {
    var sum = 0, countOfNumbers = 0
    for number in numbers {
        sum += number
        countOfNumbers++
    }
    var result: Double = sum / countOfNumbers
    return result
}

I get the following error: Could not find an overload for '/' that accepts the supplied arguments

question from:https://stackoverflow.com/questions/24181082/why-cant-i-divide-integers-in-swift

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

1 Reply

0 votes
by (71.8m points)

The OP seems to know how the code has to look like but he is explicitly asking why it is not working the other way.

So, "explicitly" is part of the answer he is looking for: Apple writes inside the "Language Guide" in chapter "The Basics" -> "Integer and Floating-Point Conversion":

Conversions between integer and floating-point numeric types must be made explicit


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

...