Instantly share code, notes, and snippets.

View kitura-helloworld.swift
import Kitura
let router = Router() router.get("/") { request, response, next in
response.send("Hello, World!")
next()
}
Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()
View login_version2.swift
func login() {
do {
let token = try loginUserWithUsername("konrad1977", password: nil)
print("user logged in \(token)")
} catch let error as LoginError {
print(error.description)
} catch {
print(error)
}
View extension.swift
extension LoginError : CustomStringConvertible {
var description: String {
switch self {
case .EmptyUsername:
return "Username cannot be empty"
case .EmptyPassword:
return "Password cannot be empty"
}
}
View login_version1.swift
func login() {
do {
let token = try loginUserWithUsername("konrad1977", password: nil)
print("user logged in \(token)")
} catch LoginError.EmptyUsername {
print("empty username")
} catch LoginError.EmptyPassword {
print("empty password")
} catch {
View login.swift
func loginUserWithUsername(username: String?, password: String?) throws -> String {
guard let username = username where username.characters.count != 0 else {
throw LoginError.EmptyUsername
}
guard let password = password where password.characters.count != 0 else {
throw LoginError.EmptyPassword
}
///Handle all the other,
return "token:" + username
View exception.swift
enum LoginError : ErrorType {
case EmptyUsername
case EmptyPassword
}
View enums.swift
enum TextCase {
case Uppercase(String)
case Lowercase(String)
}
let values: [TextCase] = [
.Uppercase("FOO"),
.Lowercase("iamlow"),
.Uppercase("BAR"),
]
View do_try_catch.swift
enum CustomError : ErrorType {
case ErrorWithMessage(message: String)
}
func loginUserWithName(username: String?) throws -> String {
guard let username = username where username.characters.count != 0 else {
throw CustomError.ErrorWithMessage(message: "No username provided")
}
return "token:" + username
View guard.swift
func greetingsForOptionals(name: String?) {
guard let unwrappedName = name where unwrappedName.characters.count != 0 else {
return
}
print("Greetings \(unwrappedName)")
}
var name: String? = "FooBar"
greetingsForOptionals(name)
View repeat.swift
var index = 0
repeat {
index++
} while index < 100