Nine iOS notes from November 2019, checked again: removing symbols from a string (and why [^A-Za-z0-9] drops "é"); SF Symbols with no #available check on iOS 13 and later; running code after the Back button with isMovingFromParent; Realm 4.0's update: change, where true maps to .all, not .modified; a property wrapper that compiles, for UserDefaults; downloading one folder from GitHub with git sparse-checkout; NFC and readingAvailable; sizing SF Symbols; and UserDefaults suites, tested.
SWIFT TIPS · SWIFT 5.1 · 9 NOTES
First posted on November 19, 2019, as "9 Notes In November 2019". Rewritten on November 19, 2026, seven years to the day. The tests were run as Mac Catalyst programs with Swift 6.2.3 (Xcode 26.2, Swift 5 mode) on macOS 26.0.1, with a test UserDefaults suite that was deleted afterwards, and every code block was type-checked for an iOS 15 target. The Git commands were run on a local repository. The NFC code wasn't run, because a Mac can't read NFC tags. Nothing was run on an iPhone or a simulator.
November 2019 was a few weeks after Xcode 11 and Swift 5.1 came out, and the new things show up: SF Symbols, property wrappers, Realm 4.0. The rest is a regex, navigation, a browser extension, NFC on an old phone, and UserDefaults.
Two of the code samples didn't compile as posted. The property wrapper had no wrappedValue, and the SF Symbols line was missing a bracket. Both are fixed and tested below, along with a UserDefaults test that turned out differently from what I expected.
1. Keep only letters and digits
2019: replacingOccurrences(of: "[^A-Za-z0-9]+", with: "", options: .regularExpression), from Stack Overflow, turns _<$abc$>_ into abc.
Now: still a good one-liner. The test adds an invoice number and a word with an accent:
"_<$abc$>_" [^A-Za-z0-9]+ -> "abc" [^\p{L}\p{N}]+ -> "abc"
"INV-2019/11#42" [^A-Za-z0-9]+ -> "INV20191142" [^\p{L}\p{N}]+ -> "INV20191142"
"Caf\u{E9} 50%" [^A-Za-z0-9]+ -> "Caf50" [^\p{L}\p{N}]+ -> "Caf\u{E9}50"
The ASCII pattern turned "Café" into "Caf", because "é" isn't in A-Za-z. That's right for codes and IDs, and wrong for names, where \p{L} (any letter) and \p{N} (any digit) keep the accent:
import Foundation
extension String {
/// Keeps A-Z, a-z and 0-9 only: "INV-2019/11#42" -> "INV20191142".
var asciiAlphanumerics: String {
replacingOccurrences(of: "[^A-Za-z0-9]+", with: "", options: .regularExpression)
}
/// Keeps letters and digits from any script, so "Caf\u{E9}" keeps its accent.
var lettersAndDigits: String {
replacingOccurrences(of: "[^\\p{L}\\p{N}]+", with: "", options: .regularExpression)
}
}
Pick by what the text is for. A voucher code should be ASCII; a person's name should keep its letters.
2. SF Symbols and #available
2019: if #available(iOS 13.0, *), use UIImage(systemName: "bolt.slash"); otherwise an image from the asset catalog.
Now: with a deployment target of iOS 13 or later, the check is always true and can go. The 2019 code also had a missing closing bracket after the image literal. One thing remains: UIImage(systemName:) returns an optional, and a typo gives nil, not an error:
UIImage(systemName: "bolt.slash"): found
UIImage(systemName: "bolt.slashh") (typo): nil
So check symbol names in the SF Symbols app, and give a fallback where a missing icon would hurt. Newer symbols also have a minimum iOS version, shown in the app; on an older system they come back nil. The code is with note 8.
3. Run code after the Back button
2019: make the second view controller the navigation controller's delegate, and in navigationController(_:didShow:animated:) check whether the shown view controller is the first one, then push another screen.
Now: that works until something else also wants to be the navigation controller's delegate; there's only one. It also had a typo, EvenKitViewController in one place and EventKitViewController in another, which wouldn't compile. A simpler way is to ask the screen being left. isMovingFromParent is true in viewWillDisappear and viewDidDisappear only when the screen is being removed from its parent, which for a pushed screen means popped:
import UIKit
final class EventDetailViewController: UIViewController {
/// Set by whoever pushes this screen.
var onBack: (() -> Void)?
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// True only when this screen is popped (Back button or swipe), not when another is pushed.
if isMovingFromParent {
onBack?()
}
}
}
final class EventListViewController: UIViewController {
func showDetail() {
let detail = EventDetailViewController()
detail.onBack = { [weak self] in
self?.navigationController?.pushViewController(ScannerViewController(), animated: true)
}
navigationController?.pushViewController(detail, animated: true)
}
}
final class ScannerViewController: UIViewController {}
The closure lets the screen that pushed it decide what happens, which keeps the detail screen reusable. I type-checked this but couldn't run it, because the disappear callbacks need a window. The check is in viewDidDisappear because a swipe back that the person cancels halfway can call viewWillDisappear without the screen actually leaving.
4. Realm 4.0: update: true no longer compiles
2019: after pod update took Realm from 3.20.0 to 4.0.0, realm.add(object, update: true) failed with "Cannot convert value of type 'Bool' to expected dictionary value type 'String'". The fix was update: .modified.
Now: Realm 4.0.0, released on November 8, 2019, removed everything that had been deprecated, and today's Realm source keeps the Boolean update: only as an unavailable stub. Its message says "Pass .error, .modified or .all rather than a boolean", and goes on to say that .error matches false and .all matches true.
So the exact replacement for update: true is .all, not .modified. The difference, from the same source: .all writes every property and reports them all as changed; .modified writes only the properties whose values differ, so change notifications list just those. .modified is usually what you want, and it was a fine fix, but if any code relied on every property being reported, .all keeps the old behavior:
try realm.write {
realm.add(user, update: .modified) // only changed properties
// realm.add(user, update: .all) // same as the old update: true
}
I didn't compile this, since Realm isn't installed here. The error message in the screenshot is a confusing one: the compiler tried other overloads and reported a type mismatch from one of them, instead of saying the Boolean version is gone.
5. Property wrappers in Swift 5.1
2019: property wrappers arrived in Swift 5.1. Three Medium links and a short example, a @propertyWrapper struct with only private let print = "".
Now: that example doesn't compile. A property wrapper must have a wrappedValue:
Wrapper.swift:2:8: error: property wrapper type 'MyProperty' does not contain a non-static property named 'wrappedValue'
The classic first wrapper is the one the linked articles built, a UserDefaults key with a default value:
import Foundation
@propertyWrapper
struct UserDefault<Value> {
let key: String
let defaultValue: Value
var store: UserDefaults = .standard
var wrappedValue: Value {
get { store.object(forKey: key) as? Value ?? defaultValue }
set { store.set(newValue, forKey: key) }
}
}
struct Settings {
@UserDefault(key: "onboardingDone", defaultValue: false) var onboardingDone: Bool
@UserDefault(key: "fontSize", defaultValue: 17.0) var fontSize: Double
}
// var settings = Settings(); settings.fontSize = 20
// Values must be property-list types: Bool, numbers, String, Data, Date, arrays and dictionaries of them.
I tested it with a separate suite instead of .standard, which is why the wrapper takes a store:
before: false 17.0
after setting: true 20.0 | raw value in the store: 20
The default came back before anything was saved, and the saved values after. UserDefaults only stores property list types, so this wrapper isn't for your own structs unless you encode them to Data first.
6. Download one folder from GitHub
2019: the GitZip Chrome extension, to download only the folders or files you need from a GitHub repository instead of the whole project.
Now: for a single file, GitHub's file page has a Download raw file button. For a folder, Git itself can do it with a sparse checkout, with no browser extension that needs access to your GitHub pages. I ran it on a local repository with folders for sources, docs and examples:
$ git clone --filter=blob:none --sparse <repository URL> demo # a local test repository in this run
$ git sparse-checkout set Examples/Login
$ find . -path ./.git -prune -o -type f -print
./Examples/Login/LoginView.swift
./README.md
Only the chosen folder and the files at the top level were checked out. With a hosting service, --filter=blob:none also skips downloading the contents of files you didn't ask for; my local test repository didn't support filtering, so it ignored that part. You also get a real Git checkout, so git pull updates the folder later.
7. NFC on an iPhone 6s
2019: I tried Core NFC on an iPhone 6s and the session ended with "Session invalidated unexpectedly", error code 202. A third-party page said that model can't read NFC tags.
Now: Apple's Core NFC documentation doesn't list devices; it says to check readingAvailable before starting a reader session. That's the fix for the 2019 code too: check first, and tell the person the device can't do it, instead of starting a session that fails:
import CoreNFC
import UIKit
final class TagReaderViewController: UIViewController, NFCNDEFReaderSessionDelegate {
private var session: NFCNDEFReaderSession?
@objc func scanTapped() {
guard NFCNDEFReaderSession.readingAvailable else {
// Older iPhones, iPads and the simulator end up here.
let alert = UIAlertController(title: "NFC not available",
message: "This device can't read NFC tags.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
return
}
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
session?.alertMessage = "Hold your iPhone near the tag."
session?.begin()
}
nonisolated func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
print("records:", messages.flatMap(\.records).count)
}
nonisolated func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("session ended:", error.localizedDescription)
}
}
Reading also needs the Near Field Communication Tag Reading capability and an NFCReaderUsageDescription in Info.plist. I couldn't run this, since NFC reading isn't available on a Mac; the iOS 26 SDK marks readingAvailable unavailable on macOS.
8. SF Symbol sizes
2019: UIImage.SymbolConfiguration(pointSize: 12) to make a smaller symbol for a tab bar item and an image view.
Now: still how it's done, and the configuration can also set the weight, a scale, or a text style. The image sizes on this Mac:
pointSize 12 -> (14.5, 13.5)
pointSize 24 -> (29.0, 26.0)
pointSize 12, bold, scale .large -> (19.5, 18.5)
textStyle .body (follows Dynamic Type) -> (20.5, 18.5)
The point size is the size of the font the symbol is drawn with, so the image is a little bigger than that number and its shape decides the exact size. A text style follows Dynamic Type, which suits symbols next to text:
import UIKit
@MainActor
func configureIcons(imageView: UIImageView, scanController: UIViewController) {
// Deployment target iOS 13 or later: no #available check needed.
imageView.image = UIImage(systemName: "bolt.slash") ?? UIImage(named: "bolt_slash_fallback")
imageView.preferredSymbolConfiguration = UIImage.SymbolConfiguration(textStyle: .body)
let small = UIImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
let icon = UIImage(systemName: "qrcode.viewfinder", withConfiguration: small)
scanController.tabBarItem = UITabBarItem(title: "Scan", image: icon, tag: 1)
}
9. UserDefaults with a suite
2019: UserDefaults(suiteName: "name_groups") to group values, with removeObject(forKey:) for one key and removePersistentDomain(forName:) for the whole group. The example called the second one on UserDefaults.standard, inside a timer started from another repeating timer.
Now: I tested the removals with a throwaway suite:
after removeObject(forKey: "key1"): ["nil", "two", "three"]
after UserDefaults.standard.removePersistentDomain(forName: suite): ["nil", "nil", "nil"]
after suite.removePersistentDomain(forName: suite): ["nil", "nil", "nil"]
UserDefaults(suiteName: "group.com.example.app") created: true (no App Group entitlement here)
I expected the 2019 call on .standard to miss, but it cleared the suite too: removePersistentDomain(forName:) takes the domain's name, whichever instance you call it on. The nested timers were the real bug: every five seconds the outer timer started a new inner one, and neither was ever stopped. Two more points. A suite is not the same as an App Group: to share values with a widget or extension, the suite name must be your App Group ID, which starts with group., and the group must be added under Signing & Capabilities. Without it, as the last line shows, you still get a working suite, just a private one.
import Foundation
enum SharedSettings {
// For sharing with an extension, the name is your App Group ID, which starts with "group."
// and must be added under Signing & Capabilities. Without that it's a private suite.
static let suiteName = "group.com.example.myapp"
static var store: UserDefaults { UserDefaults(suiteName: suiteName) ?? .standard }
static func save(_ token: String) { store.set(token, forKey: "lastScan") }
static func lastScan() -> String? { store.string(forKey: "lastScan") }
static func removeLastScan() { store.removeObject(forKey: "lastScan") }
static func removeAll() { store.removePersistentDomain(forName: suiteName) }
}
What the 2019 version said
The post had four screenshots. One showed a third-party GitHub page, so I left it out. The other three are from note 4:
![]()


If this helped, you can support the blog through PayPal.
Keep reading on JR Devhub
Comments