quigs.blog

todayilearned

Quite frequently I find myself needing to import a module to gain access to a type (usually a model), but I never interact with that module again. Recently I discovered simple way to skip having to put import ModuleName at the top of my code. This trick is especially handy in SwiftUI, but works for any use case.

Here's an example, let's say a user wants to see their weight from HealthKit in either pounds or kilograms. To do so they press a button. In order to change this information we will create a mock class that interacts with the health data store and returns the current unit for the user's weight:

import HealthKit
class DataProvider: ObservableObject {
    @Published var unit: HKUnit?
    
    func replaceUnit(_ unit: HKUnit) {
        self.unit = unit
    }
}

Back in the view, we display the current unit, and provide a button to change the unit:

import SwiftUI
import HealthKit
struct ContentView: View {
    @StateObject var provider = DataProvider()
    var body: some View {
        VStack {
            Text("Unit type: \(provider.unit?.unitString ?? "<No Unit>")")
            Button("Replace Model") {
                if let unit = provider.unit?.unitString, unit == "kg" {
                    provider.replaceUnit(HKUnit(from: "lb"))
                } else {
                    provider.replaceUnit(HKUnit(from: "kg"))
                }
            }
        }
        .padding()
    }
}

This is pretty simplistic, but imagine you are working on an app with many different views, all which need access to HealthKit objects like HKUnit, HKQuantityType, or HKSampleQuery. Every time you need to create a new HealthKit object for the DataProvider to interact with, you will need to include the import statement for your View to be able to initialize a HealthKit type.

A simple solution

A nice feature of Swift is that you can initialize an object without naming it directly with .init(). Once the compiler knows about DataProvider.replaceUnit(_ unit: HKUnit) it remembers the HKUnit type contextually, which allows you to create any new HKUnit in the body of the replaceUnit method without explicitly using its type:

import SwiftUI
//import HealthKit //Not needed any more!
struct ContentView: View {
    ...

            Button("Replace Model") {
                if let unit = provider.unit?.unitString, unit == "kg" {
                    provider.replaceUnit(.init(from: "lb"))
                } else {
                    provider.replaceUnit(.init(from: "kg"))
                }
            }
        }
        .padding()
    }
}

Once you get used to typing .init instead of the type's name, your import statement lines will drop considerably.

The only catch to this approach is that you can't declare a variable and initialize the HKUnit type. It has to be done in-line as a parameter of .replaceUnit(:), meaning this won't work:

let pound = HKUnit(from: "lb")
provider.replaceUnit(pound)

#apple #todayilearned #programming #swiftui #swift #ios #developer #development #til

Every five to ten years, a popular social network gets hit with a crisis. Twitter's current Musk-y crisis feels precipitously different than its previous ones.

Today I came across a thread by John Bull that introduced me to the perfect word to describe 2022 Instagram and Twitter: The trust thermocline. It describes the sudden point in which various individuals lose trust in an an institution or organization en-masse.

I remember the glory days of Digg, Slashdot and MySpace. Suddenly they went from being huge communities with massive network effect to a shadow of a community that I no longer use. Twitter currently feels like it's teetering on that edge.

But they'll only MOVE when they hit the Trust Thermocline. The point where their lack of trust in the product to meet their needs, and the emotional investment they'd made in it, have finally been outweighed by the physical and emotional effort required to abandon it. β€” John Bull (@garius) November 3, 2022

At several points in the last 6 years I felt that the temperature of several social networks changed suddenly for the worse. In 2016 Facebook was no longer fun and I stopped participating in 2017. In 2019 I stopped following Medium content because it all sounded like self-promotional TED-Talk-Meets-LinkedIn echo chamber of pseudo-intellectual bullshit (on practically any topic).

This year alone I deactivated my Instagram in the summer when I realized it just felt like a confused TikTok of ads overwhelming my friends' posts and videos. Then just this week I re-invested my interest in Mastodon, a decentralized Twitter-like social network born in 2016 that over the last week has gained over 200,000 new users (on top of its several-hundred-thousand existing active accounts).

We shall see what the future holds for Twitter. It still has an enormous amount of momentum due to its size, but it may never be β€œthe” place it was for so many niche communities. Mastodon may not win the lion's share of the Twitter-exodus, but it stands a good chance of becoming somewhat relevant now.

Enjoy the thread and follow John on Mastodon!

One of the things I occasionally get paid to do by companies/execs is to tell them why everything seemed to SUDDENLY go wrong, and subs/readers dropped like a stone. So, with everything going on at Twitter rn, time for a thread about the Trust Thermocline /1 β€” John Bull (@garius) November 3, 2022

#news #technology #popculture #todayilearned