简体   繁体   English

类型“ Double”不符合协议“序列类型”

[英]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. 我正在使用Xcode中的Swift,并且该代码应该创建一个函数,该函数具有我告诉它的拥有/不限数量的参数。

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. 在函数内部, balances的数组类型为[Double]以便您可以迭代其元素。

Note that this can be written more compactly with reduce() : 请注意,这可以使用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. 您的代码无法编译,因为balances : Double只是一个双数,而不是数组或序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型Any不符合协议序列 - Type Any does not conform to protocol Sequence 类型“ ViewController”不符合协议 - Type 'ViewController' does not conform to protocol Swift:类型'ViewController'不符合协议'UIPageViewControllerDataSource' - Swift: Type 'ViewController' does not conform to protocol 'UIPageViewControllerDataSource' 类型“类”不符合协议“ MCSessionDelegate” - Type 'Class' does not conform to protocol 'MCSessionDelegate' 类型“SwinjectStoryboardOption”不符合协议“ServiceKeyOption” - Type 'SwinjectStoryboardOption' does not conform to protocol 'ServiceKeyOption' 类型“ WatchManager”不符合协议“ WCSessionDelegate” - Type 'WatchManager' does not conform to protocol 'WCSessionDelegate' 类型'AnyObject'不符合协议'NSFetchRequestResult' - Type 'AnyObject' does not conform to protocol 'NSFetchRequestResult' 类型'Boolean'不符合协议'BooleanType' - Type 'Boolean' does not conform to protocol 'BooleanType' Swift:`类型'[String]'不符合协议'StringLiteralConvertible' - Swift: `Type '[String]' does not conform to protocol 'StringLiteralConvertible'` 类型“myViewController”不符合Swift中的协议UIPIckerDataSource - Type “myViewController” does not conform to protocol UIPIckerDataSource in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM