Swift concurrency

This article explores how Swift concurrency works:

https://swiftsenpai.com/swift/swift-concurrency-prevent-thread-explosion/

1 Like

What would the following 8th code look like when written in Swift? It fetches and outputs the Hacker News top stories using 16 tasks. Ordering of outputted top stories is not important.


needs net/http

"https://hacker-news.firebaseio.com/v0/topstories.json" constant STORIES_URL
"https://hacker-news.firebaseio.com/v0/item/" constant ITEM_URL_BASE

16 constant NUMTASKS

var ids
var tasks

: get-ids
  STORIES_URL net:get if
    nip json> ids !
  else
    drop "Error retrieving data" throw
  then ;

: task  \ ids-slice --
  ( ITEM_URL_BASE "%s%d.json" s:strfmt net:get if
      nip json> null? if
        drop "Failed get." . cr
      else
        "title" m:_@ . cr
      then
    else
      drop "Error retrieving data." . cr
    then
  ) a:each! drop ;

: start-tasks
  a:new ( ids @ swap -1 NUMTASKS a:slice+ 1 ' task t:task-n a:push ) 0 NUMTASKS n:1- loop tasks ! ;

: wait-tasks
  tasks @ t:wait ;

: app:main
  get-ids start-tasks wait-tasks ;