Reactive Programming in iOS with Combine

Feb 4 2021 Swift 5.3, macOS 11.0, Xcode 12.2

Part 1: Getting Started

4. Challenge: Create a Blackjack Dealer

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 3. Subscriber Operators and Subjects Next episode: 5. Conclusion

This video was last updated on Feb 4 2021

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Time to put your new Combine skills to the test, and make a handy blackjack card dealer while you’re at it. In case you’re not familiar with it, blackjack is a card game where the goal is to get 21 — or as close as possible without going over, which is called getting “busted.”

let dealtHand = PassthroughSubject<Hand, HandError>()
public let cards = [
  ("🂡", 11), ("🂢", 2), ("🂣", 3), ("🂤", 4), ("🂥", 5), ("🂦", 6), ("🂧", 7), ("🂨", 8), ("🂩", 9), ("🂪", 10), ("🂫", 10), ("🂭", 10), ("🂮", 10),
  ("🂱", 11), ("🂲", 2), ("🂳", 3), ("🂴", 4), ("🂵", 5), ("🂶", 6), ("🂷", 7), ("🂸", 8), ("🂹", 9), ("🂺", 10), ("🂻", 10), ("🂽", 10), ("🂾", 10),
  ("🃁", 11), ("🃂", 2), ("🃃", 3), ("🃄", 4), ("🃅", 5), ("🃆", 6), ("🃇", 7), ("🃈", 8), ("🃉", 9), ("🃊", 10), ("🃋", 10), ("🃍", 10), ("🃎", 10),
  ("🃑", 11), ("🃒", 2), ("🃓", 3), ("🃔", 4), ("🃕", 5), ("🃖", 6), ("🃗", 7), ("🃘", 8), ("🃙", 9), ("🃚", 10), ("🃛", 10), ("🃝", 10), ("🃞", 10)
]
public typealias Card = (String, Int)
public typealias Hand = [Card]
var cardString: String {
  map { $0.0 }.joined()
}

var points: Int {
  map { $0.1 }.reduce(0, +)
}
case busted
public var description: String {
  switch self {
  case .busted:
    return "Busted!"
  }
}
func deal(_ cardCount: UInt) {
  var deck = cards
  var cardsRemaining = 52
  var hand = Hand()

  for _ in 0 ..< cardCount {
    let randomIndex = Int.random(in: 0 ..< cardsRemaining)
    hand.append(deck[randomIndex])
    deck.remove(at: randomIndex)
    cardsRemaining -= 1
  }
// Add code to update dealtHand here
// Add subscription to dealtHand here
if hand.points > 21 {
  dealtHand.send(completion: .failure(.busted))
} else {
  dealtHand.send(hand)
}
_ = dealtHand
  .sink(receiveCompletion: {
    if case let .failure(error) = $0 {
      print(error)
    }
  }, receiveValue: { hand in
    print(hand.cardString, "for", hand.points, "points")
  })