Last active
August 29, 2015 14:17
-
-
Save JadenGeller/67d02fe7b8eedfbe58a5 to your computer and use it in GitHub Desktop.
Swift Within Syntax
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
// Allows you to use || within switch statement cases :D | |
// Implicitly combines two equatable elements into a set | |
func ||<T: Equatable>(lhs: T, rhs: T) -> Set<T> { | |
return Set([lhs, rhs]) | |
} | |
// Implicitly adds an equatable element into a set | |
func ||<T: Equatable>(var lhs: Set<T>, rhs: T) -> Set<T> { | |
lhs.insert(rhs) | |
return lhs | |
} | |
// Defines pattern comparison on SequenceTypes | |
func ~=<S : SequenceType where S.Generator.Element : Equatable>(lhs: S, rhs: S.Generator.Element) -> Bool { | |
return contains(lhs, rhs) | |
} | |
// Switch statement example | |
func isFavorite(num: Int) -> Bool { | |
switch num { | |
case 1 || 2 || 3 || 11: return true | |
default: return false | |
} | |
} | |
println(isFavorite(3)) // -> true | |
println(isFavorite(8)) // -> false | |
// If statement example | |
func isGreeting(word: String) -> Bool { | |
if ("hi" || "hello" || "hey") ~= word { | |
return true | |
} | |
else { | |
return false | |
} | |
} | |
println(isGreeting("hey")) // -> true | |
println(isGreeting("bye")) // -> false | |
// Note that, in addition to the implicit set operator, ||, you can also | |
// use ~= with explicit sets and other sequence types such as arrays | |
let nums = [1, 2, 3] | |
println(nums ~= 1) | |
println(nums ~= 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment