Skip to content

Instantly share code, notes, and snippets.

@alemar11
Forked from krzyzanowskim/where-where.swift
Created November 14, 2015 14:20
Show Gist options
  • Save alemar11/f7d1a203673b9b6d9c65 to your computer and use it in GitHub Desktop.
Save alemar11/f7d1a203673b9b6d9c65 to your computer and use it in GitHub Desktop.
import Cocoa
// for-in
func checkForIn(array: [Int], dict: [Int: String]) {
for num in array where dict[num] != nil {
num
}
}
checkForIn([1,2,3,4], dict: [1:"one", 2:"two"])
// do-catch
enum MyError: ErrorType {
case Oooggh(String)
}
func errorProne() throws {
throw MyError.Oooggh("nope")
}
do {
try errorProne()
} catch MyError.Oooggh(let argument) where argument == "agree" {
print("oooggh")
} catch MyError.Oooggh(let argument) where argument == "nope" {
print("oooggh")
}
// while
func checkWhile(inout array: [Int]?) {
while let arr = array where arr.count < 5 {
array?.append(0)
}
}
var mutableArray:[Int]? = []
checkWhile(&mutableArray)
// if
func checkIf(string: String?) {
if let str = string where str == "checkmate" {
print("game over")
return
}
print("let's play")
}
checkIf("checkmate")
// guard
func checkGuard(string: String?) {
guard let str = string where str != "checkmate" else {
print("game over")
return
}
print("let's play")
}
checkGuard("checkmate")
// switch-case
var value = (1,2)
switch value {
case let (x, y) where x == 1:
// match 1
break
case let (x, y) where x / 5 == 1:
// not-match
break
default:
break
}
// generics
func genericFunction<S where S: StringLiteralConvertible>(string: S) {
print(string)
}
genericFunction("lambada")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment