noname
noname

Reputation: 127

Enum switch via tuple

I am missing synatax for tuple as a case for switch enum.

public protocol QueryType {
    var predicate: NSPredicate? { get }
    var sortDescriptors: [SortDescriptor] { get }
}

 public enum Query: QueryType {
        case id(Int)
        case owner(String)
        case isSent(Bool)

        public var predicate: NSPredicate? {

            switch self {
            case .id(let value):
                return NSPredicate(format: "id == %d", value)
            case (.owner(let value1), .isSent(let value2)):
                return NSPredicate(format: "owner == %@ AND isSent == %@", value1, NSNumber(booleanLiteral: value2)
            }
        }

        public var sortDescriptors: [SortDescriptor] {
            return [SortDescriptor(keyPath: "id")]
        }
    }

In case with two conditions I am getting an error: "Tuple pattern cannot match values of the non-tuple type 'MyType.Query'"

Is it even possible ?

EDIT

What about creating case ownerIsSent(String, Bool), then in switch as a

case .ownerIsSent(let value1, let value2):
return NSPredicate(format: "owner == %@ AND isSent == %@", value1, NSNumber(booleanLiteral: value2))

Thanks in advance!

Upvotes: 0

Views: 868

Answers (2)

Daij-Djan
Daij-Djan

Reputation: 50129

the edit would work. I'd rename stuff only:

e.g.

case id(Int)
case sentByOwner(String,Bool)

You want to use Query as a factory for predicates I guess!? Then ... I think you could do this

Upvotes: 2

vadian
vadian

Reputation: 285210

That's impossible. You can switch only on one case simultaneously. Even (self, self) would switch on the same case.

A solution could be to add a case with two associated values for example

case id(Int)
case owner(String)
case isSent(Bool)
case ownerIsSent(String, Bool)

Upvotes: 2

Related Questions