Craig Otis Craig Otis - 1 year ago 92
Swift Question

Swift closure: Cannot convert value of type '(_) -> Bool' to expected argument type

I'm working with the

method in Swift, but encountering a problem I can't seem to reproduce in a playground.

Edit: Uploaded an example project here:

I have a
struct which contains a

struct Card {
var name = ""
var type : CardType

enum CardType {
case Red
case Black

And a
class which maintains an array of these

class Player {
var hand : [Card]

init() {
hand = ...

func redCards() -> [Card] {
return hand.filter({ (card) -> Bool in
return card.type == .Red

However, Xcode is throwing an error no matter how I try to format this closure. I even let Xcode autocomplete the closure signature/body, thinking I had a syntax error, but it keeps recreating it the same (correct?) way:

enter image description here

I've also tried editing what Xcode automatically generates and providing a simpler version, to no avail:

enter image description here


enter image description here

As I mention I'm unable to reproduce this in a simple playground example, but I can't narrow down what's actually causing the issue in my primary project.

This is the only error in my project, and if I comment out the method containing the
call, it builds properly.

Is this error a common red herring for some other actual issue?

Note: Using Xcode 7.3.1 (7D1014)

Answer Source

Something flakey is happing with Swift's type inference. Give card an explicit type and it will work.

return hand.filter({ (card: Card) -> Bool in return card.type == .Red })

You don't need the return type or the return:

return hand.filter({ (card: Card) in card.type == .Red })