Swift 6 Migration (#5733)

* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
This commit is contained in:
Mauro
2026-06-18 17:55:31 +02:00
committed by GitHub
parent 7edca8b5a1
commit a520d94760
444 changed files with 3677 additions and 3361 deletions
@@ -11,13 +11,13 @@
import AVKit
import Foundation
enum AVMetadataBinaryValueError: Error {
nonisolated enum AVMetadataBinaryValueError: Error {
case unhandledQRSegmentMode(UInt8)
case bitError(BitError)
case unknown(Error)
}
extension AVMetadataMachineReadableCodeObject {
nonisolated extension AVMetadataMachineReadableCodeObject {
var qrBinaryValue: Data? {
get throws(AVMetadataBinaryValueError) {
guard type == .qr else { return nil }
@@ -66,11 +66,11 @@ enum BitError: Error {
case unhandledAlphanumericCharacter(UInt8)
}
private struct Bit {
private nonisolated struct Bit {
let value: UInt8
}
private extension [Bit] {
private nonisolated extension [Bit] {
mutating func takeBits(_ count: Int) throws(BitError) -> UInt8 {
guard count <= 8 else { throw .moreThan8BitsTaken }
@@ -163,7 +163,7 @@ private extension [Bit] {
}
}
private extension Data {
private nonisolated extension Data {
func bits() -> [Bit] {
var result = [Bit]()
forEach { (byte: UInt8) in
@@ -173,7 +173,7 @@ private extension Data {
}
}
private extension UInt8 {
private nonisolated extension UInt8 {
func bits() -> [Bit] {
var bits: [Bit] = []
for i in 0..<8 {
@@ -8,7 +8,7 @@
import Foundation
extension Array {
nonisolated extension Array {
func groupBy(_ isGroupable: (Element) -> Bool) -> [[Element]] {
var newItems = [[Element]]()
@@ -60,7 +60,7 @@ extension Array {
}
}
extension Array where Element == RoomTimelineItemProtocol {
nonisolated extension Array where Element == RoomTimelineItemProtocol {
func firstUsingStableID(_ id: TimelineItemIdentifier) -> Element? {
first { $0.id.uniqueID == id.uniqueID }
}
@@ -6,8 +6,9 @@
// Please see LICENSE files in the repository root for full details.
//
extension AsyncSequence {
nonisolated extension AsyncSequence {
func first() async rethrows -> Self.Element? {
try await first { _ in true }
var iterator = makeAsyncIterator()
return try await iterator.next(isolation: #isolation)
}
}
@@ -8,7 +8,7 @@
import Foundation
extension AttributedString {
nonisolated extension AttributedString {
/// faster than doing `String(characters)`: https://forums.swift.org/t/attributedstring-to-string/61667
var string: String {
String(characters[...])
@@ -9,7 +9,7 @@
import Foundation
import Synchronization
public extension Bundle {
public nonisolated extension Bundle {
/// The top-level bundle that contains the entire app.
static var app: Bundle {
var bundle = Bundle.main
@@ -8,7 +8,7 @@
import Foundation
extension CharacterSet {
nonisolated extension CharacterSet {
private static let urlAllowedSets: [CharacterSet] = [
.urlUserAllowed,
.urlPasswordAllowed,
@@ -9,7 +9,7 @@
import Foundation
import MatrixRustSDK
extension ClientBuilder {
nonisolated extension ClientBuilder {
/// A helper method that applies the common builder modifiers needed for the app.
static func baseBuilder(setupEncryption: Bool = true,
httpProxy: String? = nil,
@@ -8,7 +8,7 @@
import Foundation
extension Collection {
nonisolated extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript(safe index: Index) -> Element? {
indices.contains(index) ? self[index] : nil
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
extension Date {
/// The date formatted with the minimal necessary units given how long ago it occurred.
func formattedMinimal() -> String {
nonisolated func formattedMinimal() -> String {
let calendar = Calendar.current
if calendar.isDateInToday(self) {
@@ -35,7 +35,7 @@ extension Date {
}
/// The date of an expiration formatted with the minimal necessary units given how long in the future it is.
func formattedExpiration() -> String {
nonisolated func formattedExpiration() -> String {
let calendar = Calendar.current
let now = Date.now
@@ -75,12 +75,12 @@ extension Date {
}
/// The date formatted as just the time, for use in timeline items specifically.
func formattedTime() -> String {
nonisolated func formattedTime() -> String {
formatted(date: .omitted, time: .shortened)
}
/// A fixed date used for mocks, previews etc.
static var mock: Date {
nonisolated static var mock: Date {
DateComponents(calendar: .current, year: 2007, month: 1, day: 9, hour: 9, minute: 41).date ?? .now
}
}
@@ -8,7 +8,7 @@
import Foundation
extension Dictionary {
nonisolated extension Dictionary {
var jsonString: String? {
guard let data = try? JSONSerialization.data(withJSONObject: self,
options: [.fragmentsAllowed, .sortedKeys]) else {
@@ -12,7 +12,7 @@ enum FileManagerError: Error {
case invalidFileSize
}
extension FileManager {
nonisolated extension FileManager {
func directoryExists(at url: URL) -> Bool {
var isDirectory: ObjCBool = false
guard fileExists(atPath: url.path(percentEncoded: false), isDirectory: &isDirectory) else {
@@ -10,7 +10,6 @@ import Compound
import HTMLParser
import SwiftUI
@MainActor
extension HTMLParserStyle {
static let elementX = HTMLParserStyle(textColor: UIColor.label,
linkColor: UIColor.link,
@@ -9,7 +9,7 @@
import Foundation
import Kingfisher
extension ImageCache {
nonisolated extension ImageCache {
static var onlyInMemory: ImageCache {
let result = ImageCache.default
result.memoryStorage.config.keepWhenEnteringBackground = true
@@ -9,7 +9,7 @@
import Foundation
/// NSRegularExpressions work internally on NSStrings, we need to be careful how we build the ranges for extended grapheme clusters https://stackoverflow.com/a/27880748/730924
extension NSRegularExpression {
nonisolated extension NSRegularExpression {
func matches(in string: String, options: NSRegularExpression.MatchingOptions = []) -> [NSTextCheckingResult] {
matches(in: string, options: options, range: .init(location: 0, length: (string as NSString).length))
}
@@ -14,26 +14,34 @@ extension Observable {
/// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0475-observed.md
///
/// - Parameter property: The key path to the property you would like to observe.
func observe<Value>(_ property: KeyPath<Self, Value>) -> AsyncStream<Value> {
AsyncStream { continuation in
let isActive = Mutex(true)
@Sendable func observe() {
@MainActor func observe<Value: Sendable>(_ property: KeyPath<Self, Value>) -> AsyncStream<Value> {
let (stream, continuation) = AsyncStream<Value>.makeStream()
let (changeSignals, changeSignaller) = AsyncStream<Void>.makeStream()
// Read and yield the initial value synchronously at subscription time,
// otherwise observers miss changes made right after creating the stream.
let initialValue = withObservationTracking {
self[keyPath: property]
} onChange: {
changeSignaller.yield()
}
continuation.yield(initialValue)
let task = Task { @MainActor in
// The signal is sent on willSet, but as this task runs on the next main
// executor job the new value will have been set by the time we read it.
for await _ in changeSignals {
let value = withObservationTracking {
self[keyPath: property]
} onChange: {
// Handle the update on the next run loop as this is willSet not didSet.
DispatchQueue.main.async {
guard isActive.withLock({ $0 }) else { return }
observe()
}
changeSignaller.yield()
}
continuation.yield(value)
}
continuation.onTermination = { _ in isActive.withLock { $0 = false } }
observe()
}
continuation.onTermination = { _ in task.cancel() }
return stream
}
}
@@ -8,7 +8,7 @@
import Foundation
extension ProcessInfo {
nonisolated extension ProcessInfo {
/// Flag indicating whether the app is running the unit tests.
static var isRunningUnitTests: Bool {
#if DEBUG
@@ -8,7 +8,7 @@
import SwiftUI
extension ProposedViewSize: @retroactive Hashable {
nonisolated extension ProposedViewSize: @retroactive Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(width)
hasher.combine(height)
@@ -46,8 +46,8 @@ extension Published.Publisher {
var iterator = values.makeAsyncIterator()
// skips the publisher's current value
_ = await iterator.next()
return await iterator.next()
_ = await iterator.next(isolation: #isolation)
return await iterator.next(isolation: #isolation)
}
}
}
@@ -9,7 +9,7 @@
import SwiftUI
import UniformTypeIdentifiers
extension String {
nonisolated extension String {
/// Returns the string as an `AttributedString` with the specified character tinted in a different color.
/// - Parameters:
/// - character: The character to be tinted.
@@ -41,7 +41,7 @@ extension String {
}
}
extension String {
nonisolated extension String {
func ellipsize(length: Int) -> String {
guard count > length else {
return self
@@ -50,7 +50,7 @@ extension String {
}
}
extension String {
nonisolated extension String {
func replacingHtmlBreaksOccurrences() -> String {
var result = self
let pattern = #"</p>(\n+)<p>"#
@@ -74,14 +74,14 @@ extension String {
}
}
extension String {
nonisolated extension String {
/// detects if the string is empty or contains only whitespaces and newlines
var isBlank: Bool {
trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
extension String {
nonisolated extension String {
static func makeCanonicalAlias(aliasLocalPart: Self?, serverName: Self?) -> Self? {
guard let aliasLocalPart, !aliasLocalPart.isEmpty,
let serverName, !serverName.isEmpty else {
@@ -91,7 +91,7 @@ extension String {
}
}
extension String {
nonisolated extension String {
var validatedFileExtension: String {
let fileExtension = (self as NSString).pathExtension
guard !fileExtension.isEmpty else {
@@ -101,7 +101,7 @@ extension String {
}
}
extension String {
nonisolated extension String {
/// Whether the first character with a strong BiDi direction is right-to-left.
/// Mirrors the Unicode BiDi "first strong" rule used by TextKit to resolve
/// paragraph direction when `baseWritingDirection` is `.natural`.
@@ -120,7 +120,7 @@ extension String {
}
}
extension String {
nonisolated extension String {
/// To be used if the string is actually a URL
var asSanitizedLink: String {
var link = self
@@ -9,7 +9,7 @@
import Foundation
import UserNotifications
extension UNNotificationContent {
nonisolated extension UNNotificationContent {
@objc var receiverID: String? {
userInfo[NotificationConstants.UserInfoKey.receiverIdentifier] as? String
}
@@ -35,7 +35,7 @@ extension UNNotificationContent {
}
}
extension UNMutableNotificationContent {
nonisolated extension UNMutableNotificationContent {
override var receiverID: String? {
get {
userInfo[NotificationConstants.UserInfoKey.receiverIdentifier] as? String
+12 -12
View File
@@ -10,7 +10,7 @@ import Foundation
// MARK: - Custom URLs
extension URL {
nonisolated extension URL {
/// The URL of the primary app group container.
static var appGroupContainerDirectory: URL {
guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: InfoPlistReader.main.appGroupIdentifier) else {
@@ -135,34 +135,34 @@ extension URL {
// MARK: Mocks
static var mockMXCAudio: URL {
nonisolated static var mockMXCAudio: URL {
"mxc://matrix.org/1234567890AuDiO"
}
static var mockMXCFile: URL {
nonisolated static var mockMXCFile: URL {
"mxc://matrix.org/1234567890FiLe"
}
static var mockMXCImage: URL {
nonisolated static var mockMXCImage: URL {
"mxc://matrix.org/1234567890ImAgE"
}
static var mockMXCVideo: URL {
nonisolated static var mockMXCVideo: URL {
"mxc://matrix.org/1234567890ViDeO"
}
static var mockMXCAvatar: URL {
nonisolated static var mockMXCAvatar: URL {
"mxc://matrix.org/1234567890AvAtAr"
}
static var mockMXCUserAvatar: URL {
nonisolated static var mockMXCUserAvatar: URL {
"mxc://matrix.org/1234567890AvAtArUsEr"
}
}
// MARK: - Helpers
extension URL: @retroactive ExpressibleByStringLiteral {
nonisolated extension URL: @retroactive ExpressibleByStringLiteral {
public init(stringLiteral value: StaticString) {
guard let url = URL(string: "\(value)") else {
fatalError("The static string used to create this URL is invalid")
@@ -177,7 +177,7 @@ extension URL: @retroactive ExpressibleByStringLiteral {
}
}
extension String {
nonisolated extension String {
/// Assumes that the string is a URL and sanitises it for use as the name of a directory.
func asURLDirectoryName() -> String {
replacingOccurrences(of: "https://", with: "")
@@ -188,7 +188,7 @@ extension String {
// MARK: - Phishing Confirmation URL
extension URL {
nonisolated extension URL {
static let confirmationScheme = "confirm"
var requiresConfirmation: Bool {
@@ -204,7 +204,7 @@ extension URL {
}
}
struct ConfirmURLParameters {
nonisolated struct ConfirmURLParameters {
static let internalURLKey = "internalURL"
static let displayStringKey = "displayString"
@@ -217,7 +217,7 @@ struct ConfirmURLParameters {
}
}
extension ConfirmURLParameters {
nonisolated extension ConfirmURLParameters {
init?(queryItems: [URLQueryItem]) {
guard let internalURLString = queryItems.first(where: { $0.name == Self.internalURLKey })?.value,
let internalURL = URL(string: internalURLString),
@@ -8,7 +8,7 @@
import Foundation
extension URLSession {
nonisolated extension URLSession {
/// The same as `data(for:delegate:)` but with an additional immediate retry if the first attempt fails.
func dataWithRetry(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) {
if let firstTryResult = try? await data(for: request, delegate: delegate) {
@@ -8,7 +8,7 @@
import UniformTypeIdentifiers
extension UTType {
nonisolated extension UTType {
/// Creates a type based on an optional mime type, falling back to a filename when this type is missing or unknown.
init?(mimeType: String?, fallbackFilename: String) {
guard let mimeType, let type = UTType(mimeType: mimeType) else {