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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…