Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created November 26, 2016 15:08
Show Gist options
  • Save ollieatkinson/44c88e065d6640339346d21001ec89bf to your computer and use it in GitHub Desktop.
Save ollieatkinson/44c88e065d6640339346d21001ec89bf to your computer and use it in GitHub Desktop.
Swift - Functions Playground
//: Playground - noun: a place where people can play
import UIKit
func helloWorld() -> Void {
print("hello, world!")
}
helloWorld()
// ---
func hello(name: String = "world") {
print("hello, \(name)!")
}
hello(name: "Digital Content")
// ---
func hello(names: String...) {
for name in names {
print("hello, \(name)!")
}
}
hello(names: "News", "BAU", "Sports")
// ---
var value = 0
func counter(_ count: inout Int) {
count += 1
}
counter(&value)
// ---
func convert(length: Float) -> (yards: Float, centimeters: Float, meters: Float) {
let yards = length * 0.0277778
let centimeters = length * 2.54
let meters = length * 0.0254
return (yards, centimeters, meters)
}
convert(length: 10)
// ---
func helloGeneric<T: CustomStringConvertible>(value: T) {
print("hello, \(value)!")
}
helloGeneric(value: 007)
// ---
func makeViewController<T: RawRepresentable>(from storyboard: T, identifier: T? = nil) -> UIViewController? where T.RawValue == String {
let storyboard = UIStoryboard(name: storyboard.rawValue, bundle: .main)
guard let identifier = identifier else {
return storyboard.instantiateInitialViewController()
}
return storyboard.instantiateViewController(withIdentifier: identifier.rawValue)
}
// ---
func hello(to name: () -> String) {
let value = name()
print("hello, \(value)!")
}
hello(to: { "Matt" })
// ---
func someName() -> String {
return "Melvin"
}
hello(to: someName)
// ---
func nestedGreeter(name: String) -> Void {
func greet(greeting: String) {
print("\(greeting), \(name)!")
}
greet(greeting: "hello")
}
nestedGreeter(name: "Rory")
// ---
func greet(greeting: String) -> (_ name: String) -> Void {
return { name in
print("\(greeting), \(name)!")
}
}
let italianGreeter = greet(greeting: "ciao")
let englishGreeter = greet(greeting: "hello")
italianGreeter("Paolo")
englishGreeter("Paolo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment