Advent of code day 1

The accompanying challenge doggie

For the first time, I started the Advent of Code challenge. I’ll be working with Swift using the AoC project template from Apple folks in GitHub, announced in the Swift discussion forums.

Got the two stars from the first day of the challenge. ? and rewarded myself with the traditional Friday pizza with red wine ??

Part two of day one required some interpretation. I finally got the idea and finished with success.

Don’t want to spoil the challenge but I did the part two in two different ways:

  • Going through the input string using String.Index, character by character, picking up words of numbers (“one” etc) converting them to digits (“1”) to a result string. This should be O(n) where n is the number of chars in the input data string.
  • Replacing words using Swift String replaceOccurrences using two different Dictionaries. This has two consecutive for loops iterating two dictionaries replacing text in input string using keys in dictionaries (eg “oneight”) with values (“18”) in dictionaries. This should be O(n*m) where m is the number of entries in the two dictionaries (ca 15 +/- some), n being the number of characters in the input string.

Surprisingly, the first option took 12 secs as using the higher APIs took only 0.007 secs. Maybe I did the first wrong somehow or Swift String index operations are really slow here because of Unicode perfectness. I’ve understood that the collections APIs used with strings are not so picky about Unicode correctness.

Otherwise I used conditional removal of characters that are letters from the string, map algorithms to map the strings containing numbers to integers and reduce algorithm to calculate the sum.

Challenges like this are a good way to brush up my skills. And learn more about Swift. I added myself to the Swift leaderboard to see how other Swift programmers do.

Tomorrow is the day two. Should have time for that in the morning since I wake up early nowadays, both because of myself and the dog. He is already 14+ years and having health issues unfortunately. Meaning early wake-ups every now and then.

The end part of the AoC maybe a real challenge because of all the Christmas hassle in the house. And the busy end of the semester at the university. Interesting to see how far I get and with how many gaps.

Today I was [too many] years old…

…when I learned how to localise strings containing plural values using string dictionaries (.stringsdict) in Xcode.

I am working on a terminology app teachers could use to write basic terminologies about the courses they teach. Then they could share those to the students to aid in learning the course topics. Student can also add new terms to the terminology if they wish on their own devices. And even create their own terms and terminologies. Users can also share the terminologies to others.

Anyways, I wanted to localise this at least to Finnish and English. I was supervising three localisation related student software engineering projects this Spring, so I guess that also motivated me to learn more.

Anyways, I already knew from before how to do simple localisation, but not how to localise singular and plural forms of text using string dictionaries. Finally I decided to take a shot at it, and here is the result, in Finnish first. The localised text is on the left side list, on the second gray text row of each list item:

Screenshot of a app view with localised text in Finnish, the number of elements pluralised.
The list on the left is localised from English to Finnish, using string dictionaries to pluralise the count of elements (gray text on second line of list items). The string dictionary XML is visible in the background in Xcode editor.

Below is the English version. Note that the actual contents of the app has been written in Finnish, so the main text in first line of the list is of course Finnish – only the descriptive text (“Category has 40 terms” or “No terms in this category”) is localised. And pluralised, which was the main goal here.

Screenshot of a app view with localised text in English, the number of elements pluralised.
English localisation of the same view.

This was bit of a fight (as usual), since the documents are there but no single document shows in one place a) how to specify the string dictionary and b) how to use it from code in SwiftUI. I managed to write the XML file using Apple documentation, but couldn’t find a usage sample there.

So I searched the internet and browsed Stack overflow. Then it came to my mind that surely I have some sample app or open source app on my machine where string dictionaries are used. So I searched from the directory under which I have all the source code:

find ./ -name "*.stringsdict" -print

And found that the NetNewsWire RSS reader app (highly recommended!) that I cloned from GitHub some time ago uses it. Then I dug into the source code and saw a sample from there. This and some stack overflow discussions helped me to finish the job.

So here is a sample of the string dictionary (Finnish version):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
   <dict>
      <key>term(s) in category</key>
         <dict>
            <key>NSStringLocalizedFormatKey</key>
            <string>%#@terms@</string>
            <key>terms</key>
            <dict>
               <key>NSStringFormatSpecTypeKey</key>
               <string>NSStringPluralRuleType</string>
               <key>NSStringFormatValueTypeKey</key>
               <string>lld</string>
               <key>one</key>
               <string>Kategoriassa on yksi termi</string>
               <key>other</key>
               <string>Kategoriassa on %lld termiä</string>
               <key>zero</key>
               <string>Ei termejä tässä kategoriassa</string>
            </dict>
        </dict>
    </dict>
</plist>

And this is how to use it from code — the actual beef of the whole thing. All the complexity above is to make the code simple, even though you would add support for tens of different languages to the app.

First the actual Text element in SwiftUI view that shows the localised and pluralised text:

   Text(categorySubTitle())
       .foregroundColor(.secondary)

And the function categorySubTitle() that does the formatting:

private func categorySubTitle() -> String {
   let format = NSLocalizedString("term(s) in category", comment: "");
   return String.localizedStringWithFormat(format, category.termCount)
}

Simple — when you finally get the pieces together.

Hopefully I’ll get the app finished by Fall to be used by students and staff who find if useful. As a bonus, this will be a topic for a new demonstration in a GUI programming course I am participating as an assistant teacher next Spring.

There’s one potential obstacle though — seeing the new SwiftData and other new stuff coming out this week from WWDC2023 are soooo tempting….

But if I start working using those betas, I’d have to redo lots of stuff. Though since I am already using Core Data, that shouldn’t take too long. There is also the issue that then the apps (this works on macOS, iOS and iPadOS, sharing data via iCloud) would require macOS 14 Sonoma and iOS 17, and that might leave out many users who cannot upgrade or haven’t upgraded by the time courses begin… And I’d also pay some time to refactor the Java version too, that also needs some attention.

Oh well. But now some pizza ? and red wine ?!