Skip to content

Instantly share code, notes, and snippets.

@marianolatorre
Created October 23, 2016 13:20
Show Gist options
  • Save marianolatorre/a30675db8cd79e637d437b3440543575 to your computer and use it in GitHub Desktop.
Save marianolatorre/a30675db8cd79e637d437b3440543575 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
// arrays are implemented with structs which are value types therefore when assigned they get copied.
let a = [1,2,3,4,5]
var b = a
b.append(6)
print(a)
// you cannot sum numbers of different type
let op1: Int = 1
let op2: UInt = 2
let op3: Double = 3.34
var result = Double(op1) + Double(op2) + op3
// how to unwrap properly
func printString(string: String) {
print(string)
}
var defaults = UserDefaults.standard
if let up = defaults.string(forKey: "userPref") {
printString(string: up)
}
let userPref = defaults.string(forKey: "userPref")
if userPref != nil {
printString(string: userPref!)
}
// what's the order of count in String? O(n) reason: each character could be multiple unicode items so it needs to go one by one checking.
let someString = "mariano"
print(a.count)
// Enum
//raw values: 1 2 3
// associated values can be different per instance. raw values only one per case
enum IntEnum : Int {
case ONE = 1
case TWO = 2
case THREE = 3
}
let g : IntEnum = IntEnum.ONE
let gRawValue : Int = g.rawValue
let f : IntEnum? = IntEnum(rawValue: 2)
enum assosEnum {
case NOTHING
case WITH_INT(value : Int)
case WITH_MORE_STUFF (value: Int, txt :String, data: [Float] )
}
let h : assosEnum = assosEnum.WITH_MORE_STUFF(value: 2, txt: "asd", data: [1.0, 2.3])
print(h)
// anyObject is a protocol to point to any "reference type". you cannot use it for value types like structs.
// how can these elements be added to an array of AnyObject still then?
//var array = [AnyObject]()
//array.append(1)
//array.append(2.0)
//array.append("3")
//array.append([4, 5, 6])
//array.append([7: "7", 8: "8"])
let names = ["alan","brian","charlie"]
let csv = names.reduce("===") {text, name in "\(text),\(name)"}
print(csv)
struct Planet {
var name: String
var distanceFromSun: Double
}
let planets = [
Planet(name: "Mercury", distanceFromSun: 0.387),
Planet(name: "Venus", distanceFromSun: 0.722),
Planet(name: "Earth", distanceFromSun: 1.0),
Planet(name: "Mars", distanceFromSun: 1.52),
Planet(name: "Jupiter", distanceFromSun: 5.20),
Planet(name: "Saturn", distanceFromSun: 9.58),
Planet(name: "Uranus", distanceFromSun: 19.2),
Planet(name: "Neptune", distanceFromSun: 30.1)
]
let result1 = planets.map { $0.name }
let result2 = planets.reduce(0) { $0 + $1.distanceFromSun }
print(result1)
print(result2)
// unowned or weak?
//unowned: the reference is assumed to always have a value during its lifetime - as a consequence, the property must be of non-optional type.
//weak: at some point it’s possible for the reference to have no value - as a consequence, the property must be of optional type.
class Master {
lazy var detail: Detail = Detail(master: self)
init() {
print("Master init")
}
deinit {
print("Master deinit")
}
}
class Detail {
unowned var master: Master
init(master: Master) {
print("Detail init")
self.master = master
}
deinit {
print("Detail deinit")
}
}
func createMaster() {
var master: Master = Master()
var detail = master.detail
}
createMaster()
// Structs are value type so they cannot be mutated unles...
struct IntStack {
var items = [Int]()
mutating func add(x: Int) {
items.append(x) // Compile time error here.
}
}
// loop with ranges
for _ in 1...5 {
print("Hello")
}
// structs. why tutorial1's difficult doesnt change? (ref vs value semantics)
struct Tutorial {
var difficulty: Int = 1
}
var tutorial1 = Tutorial()
var tutorial2 = tutorial1
tutorial2.difficulty = 2
// var vs let. Why mutating view2 compiles?
import UIKit
var view1 = UIView()
view1.alpha = 0.5
let view2 = UIView()
view2.alpha = 0.5 // Will this line compile?
// simplify:
//let animals = ["fish", "cat", "chicken", "dog"]
//let sortedAnimals = animals.sorted { (one: String, two: String) -> Bool in
// return one < two
//}
let sortedAnimals = ["fish", "cat", "chicken", "dog"].sorted()
print(sortedAnimals)
// whats the difference between these two lines? (nil is syntaxis sugar of second)
var optional1: String? = nil
var optional2: String? = .none
// where does the following code fail? a mutating method of a struct can only be called when declaring the struct as var (not let).
public class ThermometerClass {
private(set) var temperature: Double = 0.0
public func registerTemperature(temperature: Double) {
self.temperature = temperature
}
}
let thermometerClass = ThermometerClass()
thermometerClass.registerTemperature(temperature: 56.0)
public struct ThermometerStruct {
private(set) var temperature: Double = 0.0
public mutating func registerTemperature(temperature: Double) {
self.temperature = temperature
}
}
var thermometerStruct = ThermometerStruct()
thermometerStruct.registerTemperature(temperature: 56.0)
// Clousure capture list
var thing = "cars"
let closure = { [thing] in
print("I love \(thing)")
}
thing = "airplanes"
closure()
var thing2 = "cars"
let closure2 = {
print("I love \(thing2)")
}
thing2 = "airplanes"
closure() // Prints "I love airplanes"
// Extension using where to specify that the array elements will conform to protocol
extension Array where Element: Comparable {
func countUniques() -> Int {
let sorted = self.sorted()
let initial: (Element?, Int) = (.none, 0)
let reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
return reduced.1
}
}
var myArray = [2,3,1,2,3].countUniques()
// guard, avoid to force unwrap
func divide(dividend: Double?, by divisor: Double?) -> Double? {
guard let divisor = divisor ,
let dividend = dividend,
divisor == 0 else {
return .none
}
return dividend / divisor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment