Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 ResponseError: ErrorType {
case HTTP(Int)
}
func errorProne() throws {
throw ResponseError.HTTP(404)
}
do {
try errorProne()
} catch ResponseError.HTTP(let code) where code >= 400 && code % 2 == 0 {
print("400 Bad Request") // match
} catch ResponseError.HTTP(let code) where code >= 500 && code < 600 {
print("Internal Server Error")
}
// 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")
@DevAndArtist

This comment has been minimized.

Show comment
Hide comment
@DevAndArtist

DevAndArtist Nov 13, 2015

// partial type extension

protocol SomeProtocol {}

protocol MyProtocol {}  
extension MyProtocol where Self: SomeProtocol {  

    func foo () {
       // do something
    }
}

DevAndArtist commented Nov 13, 2015

// partial type extension

protocol SomeProtocol {}

protocol MyProtocol {}  
extension MyProtocol where Self: SomeProtocol {  

    func foo () {
       // do something
    }
}
@darren102

This comment has been minimized.

Show comment
Hide comment
@darren102

darren102 Nov 18, 2015

In the switch case blocks you do not need the 'break' when in the first two since swift will not automatically flow through them.

darren102 commented Nov 18, 2015

In the switch case blocks you do not need the 'break' when in the first two since swift will not automatically flow through them.

@krzyzanowskim

This comment has been minimized.

Show comment
Hide comment
@krzyzanowskim

krzyzanowskim Nov 25, 2015

@darren102 break is required here for noop.

Owner

krzyzanowskim commented Nov 25, 2015

@darren102 break is required here for noop.

@DevAndArtist

This comment has been minimized.

Show comment
Hide comment
@DevAndArtist

DevAndArtist Apr 17, 2016

@krzyzanowskim another way to write noop could look like this default: ()

DevAndArtist commented Apr 17, 2016

@krzyzanowskim another way to write noop could look like this default: ()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment