Reactive Programming in iOS with Combine

Feb 4 2021 · Swift 5.3, macOS 11.0, Xcode 12.2

Part 1: Getting Started

04. Challenge: Create a Blackjack Dealer

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 03. Subscriber Operators and Subjects Next episode: 05. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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")
  })