简体   繁体   中英

Type 'Double' does not conform to protocol 'Sequence Type'

This is my code and I don't know why it's not working. The title is what the error says. I'm working with Swift in Xcode and the code is supposed to create a function with as many parameters as I tell it to have/unlimited.

func addMyAccountBalances(balances : Double) -> Double {
    var result : Double = 0

    for balance in balances {
        result += balance
    }
}

the code is supposed to create a function with as many parameters as i tell it

What you probably want is a function taking a variable number of arguments , this is indicated by ... following the type:

func addMyAccountBalances(balances : Double ...) -> Double {
    var result : Double = 0
    for balance in balances {
        result += balance
    }
    return result
}

print(addMyAccountBalances(1.0, 2.0, 3.0))
print(addMyAccountBalances(4.5, 5.6))

Inside the function, balances has the array type [Double] so that you can iterate over its elements.

Note that this can be written more compactly with reduce() :

func addMyAccountBalances(balances : Double ...) -> Double {
    let result = balances.reduce(0.0, combine: +)
    return result
}

Your code does not compile because balances : Double is just a double number, not an array or sequence.

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