简体   繁体   中英

'Double' is not convertible to ()

I'm self-teaching myself Swift and I get an error at the return in func calculateTaxes . It says Double is not convertible to () . My question is what does () mean?

struct Expense {
    let description: String
    var amount: Double = 0.0
    var percentage: Double = 15.0
    var taxOwed: Double

init(description: String, amount: Double) {
    self.description = description
    self.amount = amount
}

func string1() -> String {
    return "I spent money on \(description) in the amount of $\(amount)"
}

func calculateTaxes(percentage: Double) {
    var taxOwed = (self.amount*(percentage/100))
    return taxOwed
}
}

You forgot to specify the return type (Double):

func calculateTaxes(percentage: Double)->Double {
    return (amount*(percentage/100))
}

What () actually means is Void, and in this case it's the function's return value (ie nothing). Functions without specified return value have return value of void, and that's why

func printHelloWorld() {
    println("Hello World")
}

is same as

func printHelloWorld() -> () { // Not good.
    println("Hello World")
}

You should never use the latter form as it gives no extra value to code and makes function declaration more ambiguous.

In your case, the problem is that function's return value is now Void even though it should be Double (taxOwed is a Double). You fix it by placing "-> Double" before curly braces:

func calculateTaxes(percentage: Double) -> Double {
    var taxOwed = (self.amount*(percentage/100))
    return taxOwed
}

For more information about functions and their return values, please read: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

I'd also recommend reading the whole The Swift Programming Language book, as it gives a lot of good information about the language in detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM