notes

Powered by 🌱Roam Garden

apolis notes (public)

type inference

let x = Person(name: "Bob", age: 10)
let y = x

swift infers y is type Person

deep vs shallow copy

let s1 = SomeStruct(name: "Bob")
var s2 = s1 //pass by value; deep copy
s2.name = "Billy"
//s1=Bob, s2=Billy
let c1 = SomeClass(name: "Joe")
var c2 = c1 //pass by ref; shallow copy
c2.name = "Jilly"
//c1=Jilly, c2=Jilly

protocol

abstract collection of behaviors

protocol SomeP {
  func foo()
  //...
}

both class and struct can conform to protocol

vargetset

computed property

var area: Float {
  get {
    return width*height
  }
  set {
    width = sqrtf(newValue)
    height = width
  }
}
print(sq.area) //uses getter 
sq.area = 225 //uses setter

lazy var

memory not allocated until needed

lazy var calculatedArray: [String] = {
  let arr = ["lorem", "ipsum"]
  return arr.reversed()
}()

property wrapper

@propertyWrapper
struct NonNegative {
    private var val = 0
    var wrappedValue: Int {
        get { return val }
        set { val = max(0, newValue) }
    }
}
struct Stock {
    @NonNegative var apples: Int
    @NonNegative var bananas: Int
}

handling errors

do-catch

try?

enum Handler: String, Error {
  case error1 = "Error message 1"
  case error2 = "Error message 2"
}
if successCondition {
  //success logic
  return 
}
else {
  throw Handler.error1
}

optional chaining

if let unwrappedAddress = state?.street?.zip? {
  print(unwrappedAddress)
}

equivalent to nested if-lets