Leading dot syntax in Swift

The “leading dot syntax” is an important feature in Swift to provide clean and concise APIs for callers. It supports enums and static members.

Let’s say we have an ItemStorage class that can store Item. We can define Item as enum:

class ItemStorage {
func store(_ item: Item) {
// store this item ...
}
}

enum Item {
case one
case two
// ...
}

At the call site, we can just use .one in the store(_:) function:

let storage = ItemStorage()
storage.store(.one)

Alternatively, we can change Item to struct and declare commonly used values as the static variables to make them available in leading dot syntax:

struct Item {
var identifier: String
}

extension Item {
static var someItem: Item { .init(identifier: "some-item") }
}

let storage = ItemStorage()
storage.store(.someItem) // dot syntax works for static members too
Read more »

Unified logging system (aka os_log)

The unified logging system (aka os_log) is the recommended way of logging by Apple. It’s pretty easy to create a logger and log messages at different levels:

import SwiftUI
import os.log

extension Logger {
static let button = Logger(subsystem: "name.haosong.OSLogDemo", category: "Button")
}

struct ContentView: View {
var body: some View {
VStack {
Button("Debug", action: {
Logger.button.log(level: .debug, "debug log")
}).padding()

Button("Info", action: {
Logger.button.log(level: .info, "info log")
}).padding()

// ...
}
}
}
Read more »

In this article we’re going to create a Swift wrapper function for a C function that use the ... syntax for variadic arguments:

int my_sum(int n, ...);

... variadic arguments syntax is not supported by default in Swift, you will get compiler errors like this:

'my_sum' is unavailable: Variadic function is unavailable

There’s a way to workaround this limitation, if you can modify the C function to take va_list as parameter.

Read more »

Installation

To sign git commits on macOS, we need to install gpg and pinentry-mac (for storing passphrase in keychain).

$ brew install gpg pinentry-mac

Setup GPG

Run the following command to set pinentry-mac as pinentry-program in ~/.gnupg/gpg-agent.conf:

$ echo "pinentry-program $(brew --prefix)/bin/pinentry-mac" >> ~/.gnupg/gpg-agent.conf

Add the following line to ~/.gnupg/gpg.conf:

use-agent
Read more »
0%