Dun*_*n C 4 tuples constants switch-statement swift
我决定使用Swift的case语句和元组。它看起来像是该语言的较酷功能之一。
我决定玩月/日/年元组。令我惊讶的是,我不能在switch语句中使用常量元组值作为案例。这是一个示例(可以粘贴到Playground中并运行)
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")
}
Run Code Online (Sandbox Code Playgroud)
注释掉的代码case joesBirthday:不会编译(如果重要的话,请在Xcode 6.3中)。下面的情况(我分别列出了joesBirthday元组的所有元素)很难输入,也很难阅读,确实可以工作)
键入此命令时,我的Playground崩溃了Xcode,再次尝试重新启动Xcode崩溃了,所以我在报告错误代码时遇到了麻烦。
好的,我终于让Xcode停止崩溃了(连续崩溃4次之后。Yayyy!)。错误是“二进制运算符~=无法应用于两个mdyTuple操作数”。
为什么要尝试使用~=操作数?不喜欢元组相等吗?
有没有一些干净的替代语法,可以让我在switch语句的情况下使用常量元组?
您可以~=为以下mydTuple类型实现运算符:
func ~=(a: mdyTuple, b: mdyTuple) -> Bool {
return a.month ~= b.month && a.year ~= b.year && a.day ~= b.day
}
Run Code Online (Sandbox Code Playgroud)
在操场上为我工作了...现在,这段代码
switch someday {
case joesBirthday:
println("one")
default:
println("two")
}
Run Code Online (Sandbox Code Playgroud)
打印“一个”。
这是运算符的定义:
infix operator ~= {
associativity none
precedence 130
}
Run Code Online (Sandbox Code Playgroud)
并为以下实现:
/// 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
Run Code Online (Sandbox Code Playgroud)