Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/67d02fe7b8eedfbe58a5 to your computer and use it in GitHub Desktop.
Save JadenGeller/67d02fe7b8eedfbe58a5 to your computer and use it in GitHub Desktop.
Swift Within Syntax
// 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