DEV Community

Lankinen
Lankinen

Posted on

CS193p Notes - Lecture 4: Grid + enum + Optionals

Grid

init (_ items: [Item], viewForItem: @escaping (Item) -> ItemView) {
    self.items = items
    self.viewForItem = viewForItem
}
  • @escaping is required because function is not used inside init but used somewhere else.
extension Array where Element: Identifiable {
  func firstIndex(matching: Element) -> Int {
    for index in 0..<self.count {
      if self[index].id == matching.id {
        return index
      }
    }
    return 0
  }
}
  • Adds new function to all Arrays where elements are identifiable
  • Name of the file Array+Identifiable tells that it's identifiable extension to Array

Enum

enum FastFoodMenuItem {
  case hamburger(numberOfPatties: Int)
  case fries(size: FryOrderSize)
  case drink(String, ounces: Int)
  case cookie
}

enum FryOrderSize {
  case large
  case small
}

let menuItem: FastFoodMenuItem = FastFoodMenuItem.hamburger(patties: 2)
  • Enums can contain extra data that's just for specific item like fries can be small or large.

Optional

enum Optional<T> {
  case none
  case some(T)
}

An optional is an enum.

var hello: String?              var hello: Optional<String> = .none
var hello: String? = "hello"    var hello: Optional<String> = .some("hello")
var hello: String? = nil        var hello: Optional<String> = .none

It's possible to get the value from optional two ways

hello! // this crashes the program in case the value is none

if let safehello = hello {
  print(safehello)
} else {
  // do something else
}

Default

hello ?? "This is default value"
  • comma in if statement is like sequential && operator meaning that the value that is assigned in first condition can be used in the second condition.
var indexOfTheOneAndOnlyFaceUpCard: Int? {
  get {
    var faceUpCardIndices = [Int]()
    for index in cards.indices {
      if cards[index].isFaceUp {
        faceUpCardIndices.append(index)
      }
    }
    if faceUpCardIndices.count == 1 {
      return faceUpCardIndices.first
    } else {
      return nill
    }
  }
  set {
    for index in cards.indices {
      if index == newValue {
        cards[index].isFaceUp = true
      } else {
        cards[index].isFaceUp = false
      }
    }
  }
}
  • When setting new value it turns all the other cards face down
  • when getting value it is going to check if there is two face up cards

@RealLankinen

Originally published here

Top comments (0)