简体   繁体   中英

Why can't I use a tuple constant as a case in a switch statement

I decided to play with Swift case statements and tuples. It looks like one of the cooler features of the language.

I decided to play with month/day/year tuples. To my surprise, I can't use a constant tuple value as a case in a switch statement. Here is an example (can be pasted into a Playground and run)

import UIKit
typealias mdyTuple = (month: Int, day: Int, year: Int)
let joesBirthday: mdyTuple = (month: 6, day: 7, year: 1978)
let someday: mdyTuple = (6, 7, 1978)

switch someday
{
  //---------
  //The line "case joesBirthday" won't compile.
  //case joesBirthday:
  //  println("Joe was born on this day"
  //---------
case (joesBirthday.month, joesBirthday.day, joesBirthday.year):
  println("Joe was born on this day")
case (joesBirthday.month, joesBirthday.day, let year):
  println("Joe is \(year-joesBirthday.year) today")
default:
  println("Some other day")
}

The commented out code, case joesBirthday: , will not compile (in Xcode 6.3, if that matters). The case below (where I list all the elements of the joesBirthday tuple separately) which is both harder to type, and harder to read, does work)

My Playground crashed Xcode when typing this up, and crashed AGAIN trying to restart Xcode, so I'm having trouble reporting the error code.

Ok, I finally got Xcode to stop crashing (after 4 crashes in a row. Yayyy!) The error is "Binary operator ~= cannot be applied to two mdyTuple operands."

Why is it trying to use the ~= operand? Aren't like tuples equatable?

Is there some clean alternative syntax that lets me use a constant tuple in a case of a switch statement?

You could implement the ~= operator for the mydTuple type like this:

func ~=(a: mdyTuple, b: mdyTuple) -> Bool {
    return a.month ~= b.month && a.year ~= b.year && a.day ~= b.day
}

That worked for me in a Playground... Now, this code

switch someday {
case joesBirthday:
    println("one")
default:
    println("two")
}

prints "one".

This is the operator's definition:

infix operator ~= {
    associativity none
    precedence 130
}

and is implemented for the following:

/// Returns `true` iff `pattern` contains `value`
func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool
func ~=<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool
func ~=<T : Equatable>(a: T, b: T) -> Bool
func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM