Short answer

Nine iOS notes from December 2019, checked again: String(n) versus String(describing:) (which prints "Optional(42)" for optionals); the ternary operator and Swift 5.9 if expressions; tab bar colors with UITabBarAppearance; formatting a CMTime, and why a QR code's timestamp isn't a duration; a popover presented by the view controller, not from inside a cell; pod install --no-repo-update before CocoaPods trunk goes read-only; stopping videos in table cells; a "_thumb" bug that turned "29_thumbs.png" into "29s.png"; and multi-line Git commit messages, tested.

SWIFT TIPS · SWIFT 5.1 · 9 NOTES

First posted on December 13, 2019, as "9 Notes In Desember 2019". Rewritten on November 19, 2026. The tests were run as Mac Catalyst programs with Swift 6.2.3 (Xcode 26.2, Swift 5 mode) on macOS 26.0.1, and every code block was type-checked for an iOS 15 target. The Git commands were run in a throwaway repository with a placeholder author name. No camera was used, so the QR code note is reasoned from Apple's documentation and a clock test, not from a real scan. Nothing was run on an iPhone or a simulator.

December 2019 is a mix of Swift basics I wanted to remember the Swift 5.1 way, a QR scanner, stickers in a popover, CocoaPods, videos in a feed, and a Git trick for longer commit messages.

One of the notes links to my own Stack Overflow answer, about videos that kept playing after leaving the screen. Rereading it seven years later, the answer was right but incomplete, so the version here covers the case it missed.

1. Int to String

2019: Swift 4.2 used String(describing: Int()) or interpolation; in Swift 5.1 use String(Int()) or interpolation.

Now: all three work for an Int, and String(n) was available long before Swift 5.1. The difference shows up with optionals:

String(n): 42 | "\(n)": 42 | String(describing: n): 42
String(describing: maybe): Optional(42) | maybe.map(String.init) ?? "-": 42
String(255, radix: 16): ff | Int("42"): Optional(42) | Int("4x2"): nil

String(describing:) is meant for debugging, so it prints "Optional(42)", which then appears in your interface if you're not careful. Interpolating an optional prints the same thing, with a compiler warning. For display, unwrap first, or use map with a fallback as above. The other direction, Int("42"), returns an optional, because the text might not be a number.

2. The ternary conditional operator

2019: question ? answer1 : answer2 as a short form of if/else, from the Swift book.

Now: still the shortest choice between two values. Swift 5.9 added if and switch expressions, which read better once there are three cases, where nested ternaries get hard to follow:

let stock = 3
let label1 = stock > 0 ? "In stock" : "Sold out"
let label2 = if stock > 10 { "In stock" } else if stock > 0 { "Only \(stock) left" } else { "Sold out" }
ternary: In stock | if expression: Only 3 left

An if expression is a language feature of the compiler, so it works with an iOS 15 deployment target as long as you build with Xcode 15 or later. Each branch must be a single expression of the same type.

3. Tab bar selected and unselected colors

2019: UITabBar.appearance() with barTintColor, unselectedItemTintColor and tintColor, or the same properties on tabBar inside a UITabBarController.

Now: those properties still exist, but since iOS 15 the tab bar uses the scroll edge appearance whenever content is scrolled to the bottom, and that's transparent by default, so a barTintColor can seem to disappear. UITabBarAppearance, set for both the standard and the scroll edge appearance, gives the same result everywhere:

import UIKit

@MainActor
func styleTabBar(_ tabBar: UITabBar) {
    let appearance = UITabBarAppearance()
    appearance.configureWithOpaqueBackground()
    appearance.backgroundColor = .black
    for layout in [appearance.stackedLayoutAppearance, appearance.inlineLayoutAppearance,
                   appearance.compactInlineLayoutAppearance] {
        layout.normal.iconColor = .lightGray
        layout.normal.titleTextAttributes = [.foregroundColor: UIColor.lightGray]
        layout.selected.iconColor = .white
        layout.selected.titleTextAttributes = [.foregroundColor: UIColor.white]
    }
    tabBar.standardAppearance = appearance
    tabBar.scrollEdgeAppearance = appearance    // iOS 15: otherwise the bar can be transparent
}

The January 2019 notes go through the tab bar changes in more detail. In the 2019 code, .mineShaft was a color from my own extension, not a system color.

4. A time from a QR code scan

2019: in metadataOutput(_:didOutput:from:), build CMTime(value: readableObject.time.value, timescale: 1000000000) and format it as hours, minutes and seconds with a CMTime extension. The result printed was "88:51:53".

Now: the extension is useful for any duration or playback position. I kept the idea, with integer arithmetic and a guard for invalid times:

import AVFoundation

extension CMTime {
    /// 95 s -> "01:35", 3605 s -> "1:00:05". Use it for durations and playback positions.
    var positionalTime: String {
        guard isNumeric else { return "--:--" }
        let total = Int(seconds.rounded())
        let hours = total / 3600, minutes = total % 3600 / 60, secs = total % 60
        return hours > 0
            ? String(format: "%d:%02d:%02d", hours, minutes, secs)
            : String(format: "%02d:%02d", minutes, secs)
    }
}

final class ScanTimer {
    private var startedAt: Date?

    func sessionStarted() { startedAt = Date() }

    /// Time from starting the camera to reading a code, which is usually what people want.
    func elapsedText(atScan date: Date = Date()) -> String {
        guard let start = startedAt else { return "--:--" }
        return CMTime(seconds: date.timeIntervalSince(start), preferredTimescale: 600).positionalTime
    }
}
host time clock now: 211:00:08 | system uptime: 211:00:08
a 95-second media time: 01:35 | one hour and five seconds: 1:00:05
2019 rebuild with timescale 1,000,000,000 from that value: 00:00 (seconds: 9.5e-05 )

The value it was given is the question. AVFoundation's header says a captured metadata object's time is the time at which it was captured, and capture timestamps are on the session's synchronization clock. That's a point on a clock, not a duration of anything, and it can also be invalid, which the guard handles. On this Mac, the host time clock, a common choice for that clock, read the same as the system uptime, 210 hours and some minutes. "88:51:53" looks like that kind of number: how long the iPhone had been running, not anything about the scan. I can't confirm that without a camera, but the code also rebuilt the time with its own timescale instead of the one the value came with, and the test shows what that does: 95 seconds became 95 microseconds. Use time.seconds directly when you need the value, and if you want "how long did the scan take", measure it yourself, as ScanTimer does.

5. A popover from a collection view cell

2019: the cell adds a tap gesture, creates the sticker view controller, configures it as a popover, and presents it with self.window?.rootViewController?.present, "because normal present makes an error".

Now: a cell has no present method, because it isn't a view controller, which explains the error. The root view controller workaround fails when the root is already presenting something, such as a navigation controller shown modally, and UIKit refuses with a warning. The cell should report the tap and let its view controller present:

import UIKit

final class StickerCell: UICollectionViewCell {
    let imageView = UIImageView()
    /// The view controller sets this and does the presenting.
    var onTapSticker: ((UIImage?, UIView) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        imageView.frame = contentView.bounds
        imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        contentView.addSubview(imageView)
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }

    @objc private func tapped() { onTapSticker?(imageView.image, self) }
}

final class StickerReviewViewController: UIViewController {
    var image: UIImage?
}

final class StickerPickerViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    func configure(_ cell: StickerCell) {
        cell.onTapSticker = { [weak self] image, sourceView in
            self?.showPreview(of: image, from: sourceView)
        }
    }

    private func showPreview(of image: UIImage?, from sourceView: UIView) {
        let preview = StickerReviewViewController()
        preview.image = image
        preview.modalPresentationStyle = .popover
        preview.preferredContentSize = CGSize(width: 140, height: 180)
        if let popover = preview.popoverPresentationController {
            popover.sourceView = sourceView
            popover.sourceRect = sourceView.bounds
            popover.permittedArrowDirections = .any
            popover.delegate = self
        }
        present(preview, animated: true)
    }

    // Keep it a popover on iPhone instead of a full-screen sheet.
    func adaptivePresentationStyle(for controller: UIPresentationController,
                                   traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        .none
    }
}

Returning .none from adaptivePresentationStyle(for:traitCollection:) keeps it a popover on iPhone, where it would otherwise become a full-screen sheet; that part of the 2019 code was right. Pointing the arrow at the whole cell with sourceRect = sourceView.bounds also replaces the 2019 arithmetic with four force unwraps.

6. pod install without updating the specs repo

2019: pod install --no-repo-update installs a new pod without updating the others, and it's faster with many pods.

Now: two corrections. pod install never updates pods that are already in Podfile.lock; it installs the locked versions. That's the difference from pod update, and pod update NAME updates one pod. What --no-repo-update skips is refreshing the local copy of the specs repo, which mattered when that meant pulling a huge Git repository. CocoaPods 1.8 moved to a CDN for the trunk specs, which made this much less of an issue.

The bigger news is the CocoaPods team's plan to make trunk read-only, planned for December 2, 2026; their post says the dates may still change. It says existing builds won't break, but no new pod versions will arrive through trunk after that. For a new project, use Swift Package Manager; for an existing one, it's a good moment to check which of your pods are also available as packages.

7. A video in a table cell keeps playing

2019: pause the player in tableView(_:didEndDisplaying:forRowAt:), my Stack Overflow answer, "the same as viewWillDisappear".

Now: didEndDisplaying handles a cell that scrolls off screen. It isn't the same as viewWillDisappear, though: when the person pushes another screen or switches tabs, the visible cells don't end displaying, so their videos keep playing, which was the original question. Doing both, and also stopping in prepareForReuse, covers every case:

import AVFoundation
import UIKit

final class VideoCell: UITableViewCell {
    let playerLayer = AVPlayerLayer()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.layer.addSublayer(playerLayer)
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }

    override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer.frame = contentView.bounds
    }

    func stop() {
        playerLayer.player?.pause()
        playerLayer.player = nil
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        stop()                                  // a reused cell must not keep the old video
    }
}

final class FeedViewController: UITableViewController {
    override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell,
                            forRowAt indexPath: IndexPath) {
        (cell as? VideoCell)?.stop()            // scrolled off screen
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // Leaving the screen doesn't end the cells' display, so stop the visible ones here.
        tableView.visibleCells.compactMap { $0 as? VideoCell }.forEach { $0.stop() }
    }
}

The 2019 code wrapped the pause in DispatchQueue.main.async, which isn't needed; table view delegate methods already run on the main thread. Setting the player to nil also lets it release the video.

8. Remove a substring from every name in an array

2019: loop over ["29_thumbs.png", "35_thumbs.png", ...], remove the range of "_thumb", and append the result. The comment said the output was 29.png, 35.png, 13.png, 24.png.

Now: I ran the 2019 loop on its own example:

2019 code: ["29s.png", "35s.png", "13s.png", "24s.png"]
remove "_thumbs": ["29.png", "35.png", "13.png", "24.png"]

The names end in "_thumbs" with an s, and the code removed "_thumb", so every result kept a stray "s". The comment showed what I meant, not what ran. Removing the exact text with map and replacingOccurrences is shorter and correct. The loop also skipped names without "_thumb" entirely, which may or may not be what you want; the August 2019 notes have a version that only changes a suffix before the extension.

9. A multi-line Git commit message

2019: open a single quote after git commit -m, press Return for each new line, and close the quote. The terminal output showed the commit summary as one line.

Now: that works in Bash and Zsh, which keep the quote open across lines. Two alternatives that are easier to type and to put in scripts: several -m flags, each a paragraph, or a here-document with -F-. I ran both in a test repository:

$ git commit -m 'Release 1.4.2' -m '- Fix AdMob banner size' -m '- Update version and build number'
$ git log -1 --format=%B
Release 1.4.2

- Fix AdMob banner size

- Update version and build number

$ git commit -F- <<'EOF' (three lines, no blank lines)
$ git log -1 --format=%B
Release 1.4.3
- Fix crash on launch
- Bump build number

$ git log --oneline
<hash> Release 1.4.3 - Fix crash on launch - Bump build number
<hash> Release 1.4.2

This also explains the 2019 output. Git treats everything up to the first blank line as the subject, and git log --oneline shows the subject joined onto one line. Without a blank line after the first line, the whole message became the subject. Leave a blank line after a short first line, which several -m flags do for you, and tools that show only the subject stay readable.

What the 2019 version said

The post had no screenshots; the terminal session from note 9 was pasted as text, and it's reproduced above with a placeholder repository.

Sources