Skip to content

Instantly share code, notes, and snippets.

@bjhomer
Created January 15, 2019 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjhomer/a3c3e5a7fd935f3b9b6adc62277afc8f to your computer and use it in GitHub Desktop.
Save bjhomer/a3c3e5a7fd935f3b9b6adc62277afc8f to your computer and use it in GitHub Desktop.
Is there a better way to do this?
enum Thing {
case empty
case int(Int)
}
let things: [Thing] = [.empty, .int(3), .int(7)]
// Surely there's a more concise way to write this `filter` closure?
let intThings = things.filter({
if case Thing.int = $0 { return true }
else { return false }
})
@bjhomer
Copy link
Author

bjhomer commented Jan 15, 2019

Things that don't work:

things.filter({ case Thing.int = $0 })
things.filter({ $0 is Thing.int })

@paulsamuels
Copy link

paulsamuels commented Jan 15, 2019

Not a pretty solution but I’ve done the following before. It tidied up the call site and could arguably be generated

enum Thing {
    case empty
    case int(Int)

    var unassociated: Unassociated {
        switch self {
        case .empty: return .empty
        case int: return .int
        }
    }

    enum Unassociated {
        case empty
        case int
    }
}

It then becomes at the call site

things.filter { $0.unassociated == .int }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment