Phffff=blog===


A Look at Swift

09 Dec 2019

I’ve been meaning to look at Swift, and I think Advent of Code is a good excuse.

$ docker run --rm -it swift
root@c3358942d62e:/# swift
error: failed to launch REPL process: process launch failed: 'A' packet returned an error: 8

Awkward.

https://github.com/apple/swift-docker/issues/9

$ docker run --privileged --rm -it swift
root@d8fe53a62296:/# swift
Welcome to Swift version 5.1 (swift-5.1.2-RELEASE).
Type :help for assistance.
  1> print("hi")
hi
  2>

I’ll try to solve the first question with Swift.

import Foundation

func proc(x: Int) -> Int {
  return x / 3 - 2
}

let lines = try String(contentsOfFile: "1.txt").split{ $0.isNewline }

var agg = 0
for line in lines {
  agg += proc(x: Int(String(line))!)
}
print(agg)

This works. Being a relatively new language, I thought there might be support for map, fold, and anonymous funtions. I was right:

import Foundation

func proc(x: Int) -> Int {
  return x / 3 - 2
}

let lines = try String(contentsOfFile: "1.txt").split{ $0.isNewline }

print(lines.map({proc(x: Int(String($0))!)}).reduce(0, +))

I now tried to solve part 2.

import Foundation

func proc(x: Int) -> Int {
  let res = x / 3 - 2
  if res > 0 {
    return res + proc(x: res)
  }
  return 0
}

let lines = try String(contentsOfFile: "1.txt").split{ $0.isNewline }

print(lines.map({proc(x: Int(String($0))!)}).reduce(0, +))

Using swift was hard at first (solving the docker issue) but it reads pretty nicely in this very simple use. I’m not sure what to think about the tagged arguments though.


View on GitHub