2017-07-16 192 views
2

我学习与收藏相关的斯威夫特高阶函数降低高阶函数。我有以下与reduce在雨燕3.0与诠释枚举

enum Coin : Int { 
    case Penny = 1 
    case Nickel = 5 
    case Dime = 10 
    case Quarter = 25 
} 

let coinArray: [Coin] = [.Dime, .Quarter, .Penny, .Penny, .Nickel, .Nickel] 

coinArray.reduce(0,{ (x:Coin, y:Coin) -> Int in 
    return x.rawValue + y.rawValue 
}) 

我收到以下错误查询:

Declared closure result Int is incompatible with contextual type _

+1

如果你觉得一个答案回答你的问题,请考虑通过点击对号接受它! – Sweeper

回答

3

让我们看看reduce是如何宣称:

public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result 

nextPartialResult类型?它是(Result, Element) -> Result。你的情况是什么类型的Result?它是Int,因为你想把整个东西减少到一个整数。

因此,传递(Coin, Coin) -> Int并没有真正在这里工作,不是吗?

你应该通过在(Int, Coin) -> Int代替。

coinArray.reduce(0,{ (x:Int, y:Coin) -> Int in 
    return x + y.rawValue 
}) 

或者干脆:

coinArray.reduce(0) { $0 + $1.rawValue } 
2

一旦你申请reduce到你下面的签名coinArray

enter image description here

问自己什么是通用的类型结果?它是coin型还是Int型?什么是nextPartialResult的类型?它是coin型还是Int型?

答案是:ResultInt和和nextPartialResult封闭“这需要类型的搜索结果在这里是Intcoin类型的其他参数的一个参数,并最终返回Int

所以写它的正确的方法是:

coinArray.reduce(0,{ (x, y) -> Int in 
    return x + y.rawValue 
}) 

或者你可能已经写了一个更有意义的意义:

coinArray.reduce(0,{ (currentResult, coin) -> Int in 
    return currentResult + coin.rawValue 
}) 

coinArray不是一个好名字。只需写coins。它是复数使得比coinArray/arrayOfCoins更具可读性!

+0

'也coinArray不是一个好名字。只需写硬币。这是多品牌比coinArray/arrayOfCoins更具可读性!'我不知道你选,最多从 – Alexander

+0

@Alexander寻找到埃里卡Sadun的[书](http://ericasadun.com/2016/12/14/buy-a- book-swift-style /),并从Apple的Swift指南中进行验证。您很少会看到类似于coinArray或arrayOfCoins的名称。 – Honey