Skip to content

Instantly share code, notes, and snippets.

@ondrej-kvasnovsky
Last active January 29, 2016 06:58
Show Gist options
  • Save ondrej-kvasnovsky/5b22dc753e9d274aac04 to your computer and use it in GitHub Desktop.
Save ondrej-kvasnovsky/5b22dc753e9d274aac04 to your computer and use it in GitHub Desktop.
Playground 1 for Swift
//: Playground
import UIKit
// variable
var str = "Hello, playground"
print(str)
// constant
let x = 1
print("Hi \(x)")
// create map
var map = ["hi": "there"]
print(map)
// create map and iterate it
var map1 = [String: Double]()
map1["x"] = 1
map1["y"] = 1
map1["z"] = 1
print(map1)
var total:Double = 0
for item in map1 {
total += item.1
if item.1 == 1 {
print("I got it")
} else {
print(item)
}
}
print(total)
// optional
let x1: String? = nil
let y: String = "Hi"
print(x1 ?? y)
// switch
let s = "A"
switch s {
case "A": print("I got A")
default: print("I do not know")
}
// for loop
for i in 0..<5 {
print(i)
}
// iterate through a map
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
// while
var n = 1
while n < 100 {
print("hi")
n++
}
// do-while
var m = 0
repeat {
m++
} while m<100
print(m)
// function
func hi(w: String) -> Void {
print(w)
}
hi("ahoj")
// multiple return values
func count(i: Int) -> (first: Int, second: Int) {
return (1, 2)
}
print(count(1))
print(count(1).0)
print(count(1).second)
// n parameters
func sum(i: Int...) -> Int {
var sum = 0
for ix in i {
sum += ix
}
return sum
}
print(sum(1, 2, 3))
// nested functions
func func1() {
var result = 0
func add() {
result++
}
add()
print(result)
}
func1()
// return function from function
func createFunction() -> (Int -> String) {
func myFunction(input: Int) -> String {
return String(input)
}
return myFunction
}
var callMe = createFunction()
var res = callMe(1)
print(res)
// function as parameter
func doIt(f: (Int -> String)) -> Void {
print(f(1))
}
doIt(callMe)
// map
var numbers = [20, 19, 7, 12]
var times3 = numbers.map { (t: Int) -> Int in
let res = 3 * t
return res
}
print(times3)
// map function in more consise way
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
// sort a list
let sortedNumbers = numbers.sort {$0 > $1}
print(sortedNumbers)
// create class
class Shape {
var name: String
var nrOfSides: Int = 0
init(name: String) {
self.name = name
}
func printName() {
print(self.name)
}
}
Shape(name: "My Shape").printName()
// inherit class
class Square: Shape {
var sideLength: Double
var other: Double {
get {
return 3 * sideLength
}
set {
sideLength = newValue
}
}
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
}
override func printName() {
print(self.name)
print(sideLength)
print(other)
}
}
Square(sideLength: 10, name: "Square Shape").printName()
// will and did set property of class
class MyClass {
var prop: String? {
willSet {
print("will set: \(newValue)")
}
didSet {
print("did set")
}
}
}
let myClass = MyClass()
myClass.prop = "Hi There"
print(myClass.prop)
// enums
enum HumanType: Int {
case Human = 1
case Alien = 2
}
print(HumanType.Alien)
print(HumanType.Alien.rawValue)
// enums with labels
enum AlienType {
case Human, Keplerer
func label() -> String {
switch self {
case .Human:
return "Creature from Earth"
case .Keplerer:
return "Creature from Kepler"
}
}
}
print(AlienType.Human.label())
print(AlienType.Keplerer.label())
// structures (structures are always copied when they are passed around in your code, but classes are passed by reference)
struct User {
var userName: String
var type: AlienType
func info() -> String {
return "\(userName) \(type)"
}
}
let user:User = User(userName: "John", type: AlienType.Keplerer)
print(user)
// other usecase for enums
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("All good", "Is here")
print(success)
let error = ServerResponse.Error("It failed")
print(error)
// protocols (all enums, structures and classes can adopt protocols)
protocol ProtocolExample {
var value1: String { get }
mutating func adjust()
}
class Protocol1: ProtocolExample {
var value1: String = "Initial Value"
func adjust() {
value1 = "Value 2"
}
}
var p1 = Protocol1()
print(p1.value1)
p1.adjust()
print(p1.value1)
struct Protocol2: ProtocolExample {
var value1: String = "Initial Value"
mutating func adjust() {
value1 = "Value 2"
}
}
var p2 = Protocol2()
print(p2.value1)
p2.adjust()
print(p2.value1)
enum Protocol3: ProtocolExample {
case Adjusted, Base
var value1: String { get {
return "Test"
}
}
mutating func adjust() -> Void{
self = Protocol3.Adjusted
}
}
var p3 = Protocol3.Base
print(p3.value1)
p3.adjust()
print(p3.value1)
// extensions to existing types
extension Int : ProtocolExample {
var value1 : String {
return "WTF: \(self)"
}
mutating func adjust() {
self += 1
}
}
print(1.value1)
// generics
func repeatItem<String>(item: String, count: Int) -> [String] {
var result = [String]()
for _ in 0..<count {
result.append(item)
}
return result
}
print(repeatItem("What is up", count: 3))
// generic can be used with classes, structs or enums
class Xxx<T> {
var value: T?
}
var xxx: Xxx<String> = Xxx()
xxx.value = "Hi there"
print(xxx.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment