Published April 17, 2023
We often need to convert between a String
value and a Data
value. I have been using the following approach for years to do this conversion:
func convert(from string: String) -> Data? {
string.data(using: .utf8)
}
func convert(from data: Data) -> String? {
String(data: data, encoding: .utf8)
}
Note, I'm only using functions here so the return types are explicit. Usually I would just call String.data(using:)
or String.init(data:encoding:)
directly. The important part is that they both return optionals.
There is a way to do this without optionals.
func convert(from string: String) -> Data {
Data(string.utf8)
}
func convert(from data: Data) -> String {
String(decoding: data, as: UTF8.self)
}
The optional-based approach dates all the way back to iOS 2 and Objective-C. The non-optional approach came in around iOS 8 along with Swift.
Published April 16, 2023
On the last two projects I worked on, I have used this extension on Optional
:
import Foundation
extension Optional {
func unwrap(orThrow error: @autoclosure () -> Error) throws -> Wrapped {
guard let value = self else {
throw error()
}
return value
}
func unwrap(or fallback: Wrapped) -> Wrapped {
guard let value = self else {
return fallback
}
return value
}
}
The unwrap(or:)
function is equivalent to, and more verbose than, the ??
operator. However, I find it works well in a chain of function calls. For example:
func fetchRecord(id: String) async throws -> Record {
Record(fragment:
try await client.fetch(query: RecordQuery(id: id))
.record
.unwrap(orThrow: ServiceError.notFound)
.fragments
.recordFragment
)
}
func fetchRecords() async throws -> [Record] {
try await client.fetch(query: RecordsQuery())
.records
.unwrap(or: [])
.map {
$0.fragments.recordFragment
}
.map {
Record(fragment: $0)
}
}
This lets me succinctly express a series of operations and transformations in a style that is similar to what you would write using Combine.
Usually, I would stop there. But I was wondering if I could merge the two functions. Something like this:
extension Optional {
func unwrap(or fallback: @autoclosure () throws -> Wrapped) throws -> Wrapped {
guard let value = self else {
return try fallback()
}
return value
}
}
That allows us to write this, just as before:
let value: String? = nil
print(value.unwrap(or: "nothing")
I wanted to be able also to write this, but it doesn't compile:
try print(value.unwrap(or: throw ServiceError.notFound))
error: expected expression in list of expressions
try print(value.unwrap(or: throw SomeError()))
^
Why doesn't that work?
I'm trying to pass throw SomeError()
as an autoclosure. This is what the Swift Programming Language book has to say about autoclosures:
An autoclosure is a closure that’s automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
So why can't we pass throw SomeError()
to as an autoclosure? It all comes down to the difference between a statement and an expression.
As a refresher:
An expression lets you access, modify, and assign values. In Swift, there are four kinds of expressions: prefix expressions, infix expressions, primary expressions, and postfix expressions. Evaluating an expression returns a value, causes a side effect, or both.
A statement groups expressions and controls the flow of execution. In Swift, there are three kinds of statements: simple statements, compiler control statements, and control flow statements.
Basically, an expression evaluates to a value and a statement does not. throw SomeError()
is a statement — specifically, a control flow statement. It does not evaluate to a value, so we can't pass it as an autoclosure.
Maybe we could do this with an overload. Let's try this:
extension Optional {
func unwrap(or error: @autoclosure () -> Error) throws -> Wrapped {
guard let value = self else {
throw error()
}
return value
}
func unwrap(or fallback: Wrapped) -> Wrapped {
guard let value = self else {
return fallback
}
return value
}
}
So now we have the same function name, unwrap(or:)
, that we can call in either of these ways:
let value: String? = nil
do {
print(value.unwrap(or: "nothing")
try print(value.unwrap(or: ServiceError.notFound))
}
catch {
print("Error: \(error)")
}
This works as expected. It prints:
Things get weird, though, when we deal with optional errors:
let error: Error? = nil
print(error.unwrap(or: ServiceError.notFound)
This fails to compile with this error:
error: ambiguous use of 'unwrap(or:)'
print(error.unwrap(or: Fail()))
^
note: found this candidate
func unwrap(or error: @autoclosure () -> Error) throws -> Wrapped {
^
note: found this candidate
func unwrap(or fallback: Wrapped) -> Wrapped {
^
This isn't the end of the world — we generally don't deal with optional errors. But I don't like leaving this sort of rough edge on an API. So I think I'll stick with my original approach: Optional.unwrap(orThrow:)
and Optional.unwrap(or:)
.
Published May 13, 2020
Computing cryptographic hashes in Swift has gotten easier in recent times. Prior to Xcode 10, it used to be difficult to import the CommonCrypto
library which did the computation. Xcode 10 added a module for that library, making it easier to do the import. But the API still looks like a C API. Using the library directly requires you to write something like this:
import CommonCrypto
import Foundation
// Compute the digest of this string:
let messageString = "The quick brown fox jumps over the lazy dog"
// Convert the string to a byte array.
let messageData = Data(messageString.utf8)
// Compute the hash using CommonCrypto.
var digestData = Data(count: Int(CC_SHA224_DIGEST_LENGTH))
digestData.withUnsafeMutableBytes { (digestBuffer: UnsafeMutableRawBufferPointer) -> Void in
messageData.withUnsafeBytes { (messageBuffer: UnsafeRawBufferPointer) -> Void in
_ = CC_SHA224(messageBuffer.baseAddress,
CC_LONG(messageBuffer.count),
digestBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self))
}
}
// Convert the digestData byte buffer into a hex string.
let digestString = digestData.map { String(format: "%02hhx", $0) }.joined()
// prints 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525
print(digestString)
That's a fair amount of boilerplate. The meat of that code — the withUnsafeMutableBytes
and withUnsafeBytes
calls — changed between Swift versions. I had to rewrite that code a few times to eliminate new compiler warnings and deprecations.
Rather than deal with that in production code, I wrote a small Swift library called HashAlgorithm
to simplify the process.
Using it is pretty simple. Instead of the code above, you just do this:
import Foundation
import HashAlgorithm
// Compute the digest of this string:
let messageString = "The quick brown fox jumps over the lazy dog"
let digest = HashAlgorithm.SHA224.digest(messageString)
// prints 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525
print(digest)
The digest(_:)
function returns a Digest
value that wraps a Data
value. Its description
property converts the data into a hex-string.
It supports all of the (non-deprecated) cryptographic hash algorithms currently provided by CommonCrypto
: SHA1, SHA224, SHA256, SHA384, and SHA512.
The library is available on Github.
Published May 13, 2020
Has Xcode stopped working for you? Builds acting funny? Autocomplete stopped working? You've quit and restarted it, cleaned the build folder, and it's still broken?
Try running this.
#!/usr/bin/env bash
set -euo pipefail
echo "Exiting Xcode"
osascript -e 'quit app "Xcode"'
echo "Deleting DerivedData"
rm -rf ~/Library/Developer/Xcode/DerivedData/*
echo "Deleting llvm module cache"
rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
echo "Relaunching Xcode"
open -a Xcode
Published May 10, 2020
I'm working on a side project that has required some on-device troubleshooting. I find myself loading a build on my phone and using it for several days. There's been a lot of trial-and-error debugging in this project, so I often run code from an experimental branch for extended periods of time. It's easy to lose track of what source configuration I have loaded on my phone at any given time.
I wanted to get a way to get the current Git revision and branch into the app. I figured a good start would be the following:
- The branch name (using
git rev-parse --abbrev-ref HEAD
)
- The abbreviated hash of the current commit (using
git rev-parse --short HEAD
)
- Whether the working copy was clean or not. I got this by checking the output of
git status -s
. If the working copy is clean (i.e., no untracked files and no changes to tracked files), that command prints nothing. If the working copy is dirty, the command prints something.
I wanted to get this information into each build, not just release builds. Getting this information from a shell script into a build is tricky. One of the problems is that you can't modify the working copy. Doing so would change the "is clean" flag. The build would always show dirty and a commit would be needed to clean it, changing the commit hash.
The approach I settled on was to write an untracked Swift file as part of the build process.
First, add generate-git-revision.sh
(see below) to your project's bin
directory (or wherever you keep your project's scripts).
#!/usr/bin/env bash
set -euo pipefail
cat <<SWIFT
//
// GitRevision.swift
//
// This file was automatically generated. Do not edit manually. It will be overwritten on every build.
//
// IMPORTANT: This file must be added to .gitignore or it will dirty the working tree every time there is a build.
//
/// Information about the current Git revision.
struct GitRevision {
/// The name of the current branch.
static let branch = "$(git rev-parse --abbrev-ref HEAD)"
/// The abbreviated hash of the current commit.
static let commit = "$(git rev-parse --short HEAD)"
/// Whether the working tree is clean. If false, indicates that there are uncommitted or untracked files in the working tree.
static let clean = $([[ -z $(git status -s) ]] && echo 'true' || echo 'false')
/// Build timestamp. Set when this file was generated at the beginning of the build process.
static let timestamp = "$(date +%Y-%m-%dT%H:%M:%S)"
/// A string summarizing the current Git revision.
static var description: String {
return "\(commit)\(clean ? "" : "-dirty") \(branch) \(timestamp)"
}
}
SWIFT
Next, in Xcode add a new Run Script build phase at the top of the list of Build Phases (directly under Dependencies). Call the new build phase Generate GitRevision.swift. Make the body of the build phase script:
"${PROJECT_DIR}/path/to/generate-git-revision.sh" > "${PROJECT_DIR}/path/to/GitRevision.swift"
Build the project. This causes the script to run and generate GitRevision.swift
.
Now, add the new GitRevision.swift
file to the project. Also add GitRevision.swift
to the project's .gitignore
file.
That's it. The generated GitRevision.swift
file will look something like this:
//
// GitRevision.swift
//
// This file was automatically generated. Do not edit manually. It will be overwritten on every build.
//
// IMPORTANT: This file must be added to .gitignore or it will dirty the working tree every time there is a build.
//
/// Information about the current Git revision.
struct GitRevision {
/// The name of the current branch.
static let branch = "development"
/// The abbreviated hash of the current commit.
static let commit = "3c747d5"
/// Whether the working tree is clean. If false, indicates that there are uncommitted or untracked files in the working tree.
static let clean = false
/// Build timestamp. Set when this file was generated at the beginning of the build process.
static let timestamp = "2020-05-10T23:03:15"
/// A string summarizing the current Git revision.
static var description: String {
return "\(commit)\(clean ? "" : "-dirty") \(branch) \(timestamp)"
}
}
If you leave that file open in Xcode when you build, you can see the property values change as the file gets regenerated.
You can now reference GitRevision.description
from your app's code to show the commit, branch, and build time.