Nine iOS and Mac notes from August 2019, checked again: showing hidden files in Finder (Command-Shift-Period, no Terminal needed); unzipping and walking folders with FileManager.enumerator, including subfolders; removing "_thumb" from file names without turning "29_thumbs" into "29s"; joining paths with appendingPathComponent instead of string concatenation; getting a picked photo's file name with public APIs; keeping only digits; strong and weak captures, with tests that show when an object is freed; tappable links in a UITextView; and the optional += error.
SWIFT TIPS · FILES · 9 NOTES
First posted on August 1, 2019, as "9 Notes in August Swift 4.2". 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, in a throwaway folder that was deleted afterwards, and every code block was type-checked for an iOS 15 target. The unzip step was type-checked against a stand-in for ZIPFoundation, not run. I didn't run the Finder command or shortcut from note 1. Nothing was run on an iPhone or a simulator.
August 2019 was about files. The code in these notes unpacked a zip of images, skipped the thumbnails and showed the rest in a collection view. Four of the nine notes are pieces of that, plus a Mac tip, a photo picker question, memory management, links in text and a Core Data error.
The file code worked for the zip I had, but it broke on folder names with spaces and on names like "29_thumbs.png". The tests below use a folder called "My Photos" on purpose.
1. Show hidden files in Finder
2019: defaults write com.apple.Finder AppleShowAllFiles true, then killall Finder; set it to false to hide them again.
Now: that still works, but there's a shortcut that needs no Terminal: in any Finder window or Open dialog, press Command-Shift-Period to show hidden files, and again to hide them. I didn't run either method on this Mac. The screenshots at the end show one small trap from 2019: killall finder in lowercase fails with "No matching processes", because the process is called Finder.
2. Unzip a file and list the images
2019: a view controller using the Zip library: Zip.quickUnzipFile, then contentsOfDirectory, skip names containing "_thumb", load each image with UIImage(contentsOfFile:), all in viewDidLoad.
Now: the Zip library's last release, 2.1.2, is from February 2022. ZIPFoundation is maintained, with release 0.9.20 in September 2025, and it adds FileManager.unzipItem(at:to:). The bigger change is where the work runs: unzipping and loading every image in viewDidLoad blocks the main thread, so the screen stays blank until it's done.
import Foundation
import ZIPFoundation // Swift package: https://github.com/weichsel/ZIPFoundation
/// Unzips into a fresh folder in Caches and returns the full-size images inside.
func unzipImages(from archive: URL) async throws -> [URL] {
try await Task.detached(priority: .userInitiated) {
let fileManager = FileManager()
let caches = try fileManager.url(for: .cachesDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let destination = caches.appendingPathComponent(UUID().uuidString, isDirectory: true)
try fileManager.createDirectory(at: destination, withIntermediateDirectories: true)
try fileManager.unzipItem(at: archive, to: destination)
return fullSizeImages(in: destination, fileManager: fileManager)
}.value
}
The unzip happens in a detached task, into a new folder in Caches, which the system may clear when storage is low; move anything you must keep to Application Support. The function it calls, fullSizeImages(in:), is in note 4. Load the images themselves lazily, in the cell, at the size the cell shows.
3. Remove "_thumb" from a file name
2019: range(of: "_thumb") and removeSubrange on a variable, shown on an array of names, which doesn't compile: an array has no range(of:).
Now: on each name it compiles, but it removes "_thumb" wherever it appears, not only at the end. I ran three approaches on the same list:
keep names without _thumb: ["1.png", "2.png"]
strip "_thumb" with range(of:) + removeSubrange: ["1.png", "1.png", "2.png", "2.png", "29s.png"]
strip only a trailing "_thumb" before the extension: ["1.png", "1.png", "2.png", "2.png", "29_thumbs.png"]
"29_thumbs.png" became "29s.png". If you want to keep the full-size images, filtering out the thumbnails is simpler than renaming them. If you need the name of the full-size file for a thumbnail, look only at a suffix before the extension, as fullSizeName(forThumbnail:) in the next note does.
4. Files in subfolders after unzipping
2019: if the zip contained a folder, list the top level, then build each subfolder's URL with URL(string: "\(documentsUrl)\(_data)") and list it again, with a tempFiles.count < 3 check to guess when that's needed.
Now: building URLs from strings is fragile. A folder name with a space is the classic failure, and whether it fails depends on the SDK:
URL(string: "\(root)My Photos") -> My Photos (exists: true)
same, parsed the pre-iOS 17 way (encodingInvalidCharacters: false) -> nil
root.appendingPathComponent("My Photos") -> My Photos (exists: true)
contentsOfDirectory (top level only): ["1.png", "1_thumb.png", "My Photos", "notes.txt"]
On a new SDK, URL(string:) percent-encodes the space and the path works; with the pre-iOS 17 rule it returns nil, and the 2019 code force-unwrapped it. appendingPathComponent works either way. Also, contentsOfDirectory only lists one level, which is why the 2019 code needed the guess. FileManager.enumerator walks every level and can skip hidden files such as .DS_Store:
import Foundation
/// All full-size PNGs under a folder, including subfolders, skipping hidden files
/// and "_thumb" copies. Run it off the main thread for big folders.
func fullSizeImages(in folder: URL, fileManager: FileManager = .default) -> [URL] {
guard let walker = fileManager.enumerator(
at: folder,
includingPropertiesForKeys: [.isRegularFileKey],
options: [.skipsHiddenFiles]) else { return [] }
return walker.compactMap { $0 as? URL }.filter { url in
let isFile = (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) ?? false
let baseName = url.deletingPathExtension().lastPathComponent
return isFile && url.pathExtension.lowercased() == "png" && !baseName.hasSuffix("_thumb")
}
}
/// "2_thumb.png" -> "2.png"; other names are returned unchanged.
func fullSizeName(forThumbnail name: String) -> String {
let url = URL(fileURLWithPath: name)
let base = url.deletingPathExtension().lastPathComponent
guard base.hasSuffix("_thumb") else { return name }
return String(base.dropLast("_thumb".count)) + "." + url.pathExtension
}
I ran this file as is on a folder with a subfolder, thumbnails, a text file and a hidden file:
files created: 1.png 1_thumb.png notes.txt My Photos/2.png My Photos/2_thumb.png My Photos/.DS_Store
fullSizeImages: ["1.png", "My Photos/2.png"]
fullSizeName: ["2.png", "2.png", "29_thumbs.png"]
Both full-size images were found, one of them inside "My Photos", and the thumbnails, the text file and .DS_Store were skipped. On iOS 16 and later, appending(path:) is the newer name for appendingPathComponent.
5. Get the file name of a picked image
2019: three cases. From the photo library, read info["UIImagePickerControllerPHAsset"] and call asset.value(forKey: "filename"). From a file URL, lastPathComponent. From the asset catalog, store the name in restorationIdentifier.
Now: value(forKey: "filename") reads a private property through key-value coding; it isn't documented and could stop working in any release. The public way is PHAssetResource, whose originalFilename is, in Apple's words, the file name from when the resource was created or imported. The image picker's PHAsset key is marked "will be removed in a future release, use PHPicker" in the iOS 26 SDK, and PHPickerViewController needs no photo library permission at all:
import Photos
import PhotosUI
import UIKit
final class PickerHost: UIViewController, PHPickerViewControllerDelegate {
func pickPhoto() {
var config = PHPickerConfiguration() // no photo library permission needed
config.filter = .images
let picker = PHPickerViewController(configuration: config)
picker.delegate = self
present(picker, animated: true)
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
guard let provider = results.first?.itemProvider else { return }
print("suggested name:", provider.suggestedName ?? "none") // usually without extension
}
}
/// When you already have a PHAsset (which needs photo library access), use its resources.
func originalFilename(of asset: PHAsset) -> String? {
PHAssetResource.assetResources(for: asset).first?.originalFilename
}
/// For a file you saved yourself, the name is part of the URL.
func fileName(of url: URL) -> String { url.lastPathComponent } // "image01.png"
The picker's suggestedName is a hint, often without the extension, not a guaranteed file name. For the asset catalog case, an image doesn't remember the name it was loaded with, so if you need it later, keep it yourself. Store it in a property of your own, not in restorationIdentifier, which is for state restoration; for UI tests, use accessibilityIdentifier.
6. Keep only the digits
2019: png.filter { "0123456789".contains($0) } turns "8.png" into "8".
Now: still the clearest way to keep ASCII digits. The test compares it with Character.isNumber, which sounds similar but isn't:
8.png "0123456789".contains: 8 isNumber: 8 Int: 8
12_thumb.png "0123456789".contains: 12 isNumber: 12 Int: 12
<U+0663>.png "0123456789".contains: isNumber: <U+0663> Int: nil
IMG-2019-08.png "0123456789".contains: 201908 isNumber: 201908 Int: 201908
isNumber also keeps digits from other scripts, such as the Arabic-Indic three, U+0663, and then Int() can't read the result. When the digits go into Int() or an ID, the 2019 filter is the right one. The last row is a reminder that a filter takes every digit, so a name with a date in it gives one long number.
7. Strong and weak references
2019: two playground examples, a closure capturing an object strongly and one capturing it with [weak ...], with an explanation copied from a Medium article. I've replaced that text with my own and linked the Swift book instead.
Now, in my words: a strong reference keeps an object alive; Swift frees an object when the last strong reference goes away. A weak reference points at an object without keeping it alive, so it's optional and becomes nil once the object is freed. I ran the two 2019 examples with a print in deinit:
init strong player
strong player plays a song
deinit strong player
init weak player
deinit weak player
weak player is already gone
The strong closure kept its player alive until the closure itself was released. The weak one didn't: the player was freed as soon as the function returned, so the closure found nil and the song never played. That's the 2019 note's "Done" with nothing printed. So weak isn't automatically better; it's for one situation, a reference cycle, where two things hold each other strongly and neither is ever freed:
after leaving scope, strong self still alive: true
deinit weak self
after leaving scope, weak self still alive: false
An object that stores a closure which captures self strongly never reached deinit. With [weak self], it was freed when the code was done with it. The common case in an app is a view controller with a stored closure or a repeating timer:
import UIKit
final class PlayerViewController: UIViewController {
var onFinish: (() -> Void)?
private var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// [weak self]: the closure is stored on self, so a strong capture would be a cycle.
onFinish = { [weak self] in
self?.dismiss(animated: true)
}
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
Task { @MainActor in self?.tick() }
}
}
private func tick() {}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
timer?.invalidate() // a repeating timer keeps running until you stop it
}
}
8. Tappable links in text
2019: a UITextView with isSelectable = true, isEditable = false, dataDetectorTypes = .link and red underlined linkTextAttributes.
Now: still how it's done. Data detectors only run in a text view that isn't editable, so isEditable = false is required, and isSelectable must be true for taps to reach the link. I type-checked this version, which also follows the person's text size:
import UIKit
@MainActor
func makeInviteTextView() -> UITextView {
let textView = UITextView()
textView.isEditable = false // data detectors only work when not editable
textView.isSelectable = true // and selectable, so links can be tapped
textView.isScrollEnabled = false
textView.dataDetectorTypes = [.link]
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.font = .preferredFont(forTextStyle: .body)
textView.adjustsFontForContentSizeCategory = true
textView.linkTextAttributes = [
.foregroundColor: UIColor.link,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
textView.text = "Hi! You are invited. https://www.jrdevhub.com"
return textView
}
The detection itself happens inside the text view, which I couldn't observe without a window, so I checked the same kind of detection with NSDataDetector on a sample sentence:
found: https://www.jrdevhub.com
found: http://www.apple.com
found: mailto:hello@example.com
It found a full URL, a bare www address and an email address. If you'd rather control exactly what's a link, set the .link attribute on parts of an attributed string instead of using data detectors.
9. "Cannot convert value of type 'String?' to expected argument type 'inout String'"
2019: firstUser.name += " - Update" on a Core Data entity failed with this error. The fix was to change @NSManaged public var name: String? to String.
Now: current Swift words the error differently:
Users.swift:5:15: error: value of optional type 'String?' must be unwrapped to a value of type 'String'
Users.swift:5:15: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
+= needs a non-optional value on the left, because it changes the value in place. Removing the question mark makes it compile, but in Core Data that's only safe if the attribute is also non-optional in the model editor and always has a value; otherwise reading a missing name can crash. The safer fix keeps the optional and says what an empty name means:
import Foundation
final class User { var name: String? }
func updateFirstUser(in users: [User]) {
guard let firstUser = users.first else { return }
firstUser.name = (firstUser.name ?? "") + " - Updated"
}
What the 2019 version said
The post had five screenshots: the Finder commands from note 1, and the Core Data error from note 9 with its code before and after the fix.

![]()
![]()


Keep reading on JR Devhub
Comments