Swift-Language


Jan. 6, 2023

Things I love about Swift after a week of JavaScript

Swift logo punching the JavaScript logo - Stable Diffusion

So, a week into JavaScript, what am I missing? The techie in me wants to say things like Automatic Reference Counting, but actually, at my junior level, I don’t run into memory management issues on the day-to-day, so what really do I miss?

Determinism

When I build an iOS app, it’s frozen in time. The functions inside are always going to stay the same. There might be a future version of iOS that won’t run it, but as long as it runs, any pure functions inside it will return the same value. The process of compiling it locks that in. Likewise, any libraries that are complied with it.

Oct. 30, 2022

Codable & JSON

encryption machine, comic 27970 - Stable Diffusion

If we mark a type with the protocol Codable, we’re specifying that this type has the capability of having it’s properties encoded to some format, and decoded back again.

So far in the #100Days this has been used to write and read data in UserDefaults, and to encode an object to send it as a URLRequest, then receive data back and create a new object from it. It’s a handy, powerful feature baked into Swift that just requires the developer to ensure any types that need this functionality comply with the Encodable and Decodable protocols that make up the Codable.

Oct. 14, 2022

Moonshot Challenges

Another few coding challenges at the end of a tutorial app in the 100 Days of SwiftUI course. The app is a sort of information app - composed of navigation views going down into more detail about the Apollo space missions. The most exciting revelation for me was how straightforward it is to pull JSON into your apps data structures.

Challenge 1

Add the launch date to MissionView, below the mission badge. You might choose to format this differently given that more space is available, but it’s down to you.

Oct. 13, 2022

Using Swift's map

“map, moon, transformation” - Stable Diffusion

In Day 39’ s Moonshot tutorial app, Paul uses .map on an array without much comment about what’s going on. I assume this might be a common concept in modern languages, but it was new to me.

First, here’s Paul’s code

    init(mission: Mission, astronauts: [String: Astronaut]) {
        self.mission = mission

        self.crew = mission.crew.map { member in
            if let astronaut = astronauts[member.name] {
                return CrewMember(role: member.role, astronaut: astronaut)
            } else {
                fatalError("Missing \(member.name)")
            }
        }
    }

Mission here contains an array of crew which is a struct with two strings, one of them being name, but self.crew (which belongs to the view we’re in) is an array of CrewMember which is a struct with a role: String and another struct astronaut. That sounds confusing, but essentially, an array of one type is being processed to return an array of another type where there’s a 1:1 relationship between the elements of each array.

Sep. 25, 2022

Ranges

I wondered aloud, in a previous post , about the differences in writing a range as

        ForEach(1..<21) {
            Text(String($0))
        }

versus

        ForEach(1...20) {
            Text(String($0))
        }

And that’s been answered in in one of the Day 34 articles. It sounds like older versions of Swift might not have allowed the second version.

Sep. 18, 2022

How to upgrade XCode and Swift

With the September release of XCode 14 and Swift 5.7 it was time for my first update - I looked in “About” for an update link but there wasn’t one - so if you’re as dense as me, the tip is to head to the Mac App Store and have a look at the Updates page.

Your current XCode version can, of course be found in the XCode | About dialogue. Mine was on 13.4.1. There’s a couple of ways of finding the Swift version - If you’ve got an XCode project open, click on the .xcodeproj in the explorer,and have a look in Build Settings for Swift Compiler - Language for the major version.

Sep. 12, 2022

Swift enums

I’ve started on the refactoring for Rock, paper, scissors . One of the things I didn’t like was using Ints to signal which shape (I’m calling the rock, or paper, or scissors hand shape a shape) was being handed around. The Int I was using was also the index into an array of the emoji’s - so if I did an off-by-one I was risking an out of bounds on the array.

Sep. 7, 2022

.self in ForEach

I’m on Day 25 of Hacking With SwiftUI, and Paul is making a point about how SwiftUI can loop over an array to build a view. He starts with this:

let agents = ["Cyril", "Lana", "Pam", "Sterling"]
VStack {
    ForEach(0..<agents.count) {
        Text(agents[$0])
    }
}

But then proposes an alternative:

let agents = ["Cyril", "Lana", "Pam", "Sterling"]
VStack {
    ForEach(agents, id: \.self) {
        Text($0)
    }
}

He explains the use of \.self here by saying

Aug. 27, 2022

Int.times()

When writing yesterday’s post about iterating through a range or collection and using the underscore to throw away the item, I had in the back of my mind that there should be a more straightforward way of doing something a number of times.

Just to re-iterate (lol), here’s the issue. If we want to print “Here’s the thing” three times, in Swift the simplest we can do is:

for _ in 1…3 { print(“Here’s the thing”) }

Aug. 26, 2022

The _ Underscore

I’ve learned (so far) an underscore can be used for a couple of things in Swift, both of them loosely translating to “doesn’t really matter”.

The first is in a parameter name for a function. Swift has a very cool feature I haven’t seen before where an argument can have a different internal and external name. As usual, this will make more sense in code. Imagine this:

func sumNumbers(firstNumber: Int, secondNumber: Int) -> Int { return firstNumber + secondNumber }

Aug. 24, 2022

Codewars / reduce

codewars.com is a “coding practice” website. You chose a language and a skill level, then it offers up a task (or kata) for you to write a suitable function. The first one it gave me was seemed too hard, so I changed my level to beginner and skipped to the next one. This was my task:

 Given an array of integers, find the one that appears an odd number of times.
 
 There will always be only one integer that appears an odd number of times.
 
 Examples
 [7] should return 7, because it occurs 1 time (which is odd).
 [0] should return 0, because it occurs 1 time (which is odd).
 [1,1,2] should return 2, because it occurs 1 time (which is odd).
 [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
 [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).

I know there’s a cool “Set” container type in Swift, so my plan was to iterate through the array, then for each number if there’s no entry in the set, then add one, but if there is, remove it. That way whatever is left in the set at the end must be in the original array an odd number of times. I was pretty pleased with myself. Here’s the code I Playground’d up:

Aug. 21, 2022

Named Loops

Here’s a neat thing I haven’t seen before. Other languages I’ve worked in haven’t had a neat way to break out of a set of nested loops to a particular loop. It’s not an issue that comes up a lot, but when it has I’ve solved it by creating a continue flag and having that as the first condition of each loop.

To explain, say if we had these two loops (in C):

Aug. 16, 2022

Protocols

The evolution of structs into class-like things that can hold properties and methods in Swift raised in my mind “what about inheritance?” - but no: structs in Swift can not use inheritance.

Swift classes implement inheritance, but only from one class; there’s no multiple inheritance. Protocols neatly address both these concerns to a large extent, but perhaps before we look at how they work, we should have a brief diversion into inheritance in C++.

Aug. 12, 2022

Rust

It’s been exciting to see some of the modern language features in Swift - it’s a real joy to work in when I think back to my C++ days which was some of the last commercial programming I did.

The buzz about Carbon got me wondering about other new languages and what might be going on with them. Rust seems to keep popping up in conversations so I thought I’d have a quick look.

Aug. 3, 2022

Chris Lattner

Thank you YouTube algorithm for this recommendation - Chris Lattner, the main author of Swift (amongst other things including LVM) chatting with Lex Fridman. Ignore the clickbait title. There is a good, brief discussion about the tradeoffs in value vs references types which is a topic I’ve been thinking a bit about this week.

Also some interesting comments about how a language delivers it’s complexity. Chris gives the funny example of what “hello world” looks like in Swift vs C++. Here’s Swift: Print("Hello world"), here’s C++:

Aug. 2, 2022

Retain Cycle

Variables and constants in Swift can be a value type (their data is copied when they are copied) or a reference type (a pointer to the data is passed when they are copied.

Structs, integers, and enums are value types, classes are reference types.

Memory management of value types is relatively straightforward - there’s a 1:1 relationship between the variable name and its data, so if the variable goes out of scope it can get the chop. With reference types, it’s possible to have several variables (or class or struct properties etc) all pointing to the data, so a more sophisticated system is needed to know when it’s safe to delete the data.

Aug. 1, 2022

Bump One

Most of the things I’ve learned so far have been familiar, interesting, or cool - but now I’ve ventured far enough into the Swift Language Programming book to find something that is definitely going to take a couple of readings to piece together.

I was surprised, then pleased with functions as first class types, and the idea of passing closures around is powerful and useful.

My current difficulty is getting my head around closures capturing variables. It was tolerable (but not safe) when I just thought of it as a pointer, but when turned out the captured variable continues to exist in some sort of zombie state even after the scope where the variable was contained has ended.

Jul. 25, 2022

Closures

I had one of those synchronicity in learning moments this morning. I am reading The Swift Book - ie The Swift Programming Language, Swift 5.7 as part of my cs193p homework, and this morning, in a coffee shop was admiring what a clear, well written explanation was given for closures . It is super well written, stepping the reader through in logical (and digestible) steps.

If you’ve never carelessly passed around a pointer to a function and caused the Blue Screen of Death, or done much multi-threaded programming, the use-case for closures, and use of them is going to be challenging at first. Then Swift’s ability to cut the syntax down to very little will be challenging.

Jul. 18, 2022

struct

Started on Day 10 of 100 days of etc etc today which is about structs. It was immediately clear when I first started looking at Swift and Swift UI that structs were going to be a big deal. I am used to structs being able to contain a collection of other types, but not methods. So I was confused at why tuples existed; that is now cleared up.

If structs can have methods as well as properties, it answers the question of why tuples exist, but immediately asks the question, why have classes since structs have all this power? I already know (from my podcast consumption) one of the answers for this is that structs are value types rather than references. When you:

Jul. 12, 2022

Tuple Pronunciation

Another advantage of the videos, that hadn’t occurred to me when I mentioned it the other day , is learning the correct pronunciation of things you’ve only ever read in books.

Apparently, tuple is pronounced two-pull, and not with the tup to rhyme with cup as I’d always imagined. Google has confirmed, so it’s not just a UK thing.