Created
February 17, 2016 12:15
-
-
Save ezura/cae656de2fd1e87e4346 to your computer and use it in GitHub Desktop.
これでパターンマッチもできる Range になりました\(^o^)/ #CodePiece
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MyForwardIndexTypeStruct { | |
var num: Int | |
init(_ num: Int) { | |
self.num = num | |
} | |
} | |
// Equatable | |
func == (lhs: MyForwardIndexTypeStruct, rhs: MyForwardIndexTypeStruct) -> Bool { | |
return lhs.num == rhs.num | |
} | |
extension MyForwardIndexTypeStruct : ForwardIndexType { | |
// _Incrementable | |
func successor() -> MyForwardIndexTypeStruct { | |
return MyForwardIndexTypeStruct(self.num+1) | |
} | |
} | |
// --- 方法 1 | |
// Swift 標準ライブラリにも幾つか定義されています。 | |
//func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool | |
extension MyForwardIndexTypeStruct : Comparable {} | |
func <(lhs: MyForwardIndexTypeStruct, rhs: MyForwardIndexTypeStruct) -> Bool { | |
print(__FUNCTION__) | |
return lhs.num < rhs.num | |
} | |
func <=(lhs: MyForwardIndexTypeStruct, rhs: MyForwardIndexTypeStruct) -> Bool { | |
print(__FUNCTION__) | |
return lhs.num <= rhs.num | |
} | |
func >=(lhs: MyForwardIndexTypeStruct, rhs: MyForwardIndexTypeStruct) -> Bool { | |
print(__FUNCTION__) | |
return lhs.num >= rhs.num | |
} | |
func >(lhs: MyForwardIndexTypeStruct, rhs: MyForwardIndexTypeStruct) -> Bool { | |
print(__FUNCTION__) | |
return lhs.num > rhs.num | |
} | |
// --- 方法 2 | |
// または自分で定義して使うこともできます。 | |
func ~= (pattern: Range<MyForwardIndexTypeStruct>, value: MyForwardIndexTypeStruct) -> Bool { | |
print(__FUNCTION__) | |
return pattern.contains(value) | |
} | |
let start = MyForwardIndexTypeStruct(1) | |
let end = MyForwardIndexTypeStruct(5) | |
let myRange: Range = start ... end | |
print("start") | |
switch MyForwardIndexTypeStruct(2) { | |
case myRange: | |
print("match") | |
default: | |
print("") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment