Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous lessons, you learned how to use modern Swift concurrency patterns — but how do you know if you’re using them in the recommended way?

Swift 6 introduces a new language mode, designed to enforce stricter concurrency checks. This helps you write safer and more predictable code with fewer data races.

Swift 6 language mode aims to achieve:

  • Stricter Concurrency Enforcement: To prevent data races — by ensuring stricter access rules for shared mutable state.
  • Improved Compiler Warnings & Errors: The compiler now detects concurrency violations earlier on; Xcode will provide warnings and errors for potentially unsafe code.
  • Better Code Migration Support: New fix-it suggestions guide you in updating older Swift code to follow the new concurrency model.

Fix-it Suggestions

When migrating to Swift 6, you might encounter compiler warnings related to concurrency.

Migrating the Weather Sample App to Swift 6

Up until this point, your weather app project has used Swift 5. However, you’ll now update the project to use Swift 6. Awesome!

Reviewing the Errors

Looking back on the previous lessons, you built a weather sample app with async/await and used actor types. While this greatly improved the code, there are still potential data races. Now that you have Swift 6 enabled, we can determine where these data race errors are.

Fixing the Errors

You’ll start with the first error in HomeViewModel.

// 1
@MainActor class HomeViewModel: ObservableObject {
  @Published var state: HomeState = .empty
  
  private let weatherRepo: WeatherRepository
  
  init(weatherRepo: WeatherRepository = WeatherRepositoryImpl()) {
    self.weatherRepo = weatherRepo
  }

  func getWeather(query: String) {
    state = .loading

    // 2
    Task {
      do {
        let weatherData = try await weatherRepo.fetchWeather(for: query)
        state = .ready(weatherData)
      } catch (_) {
        state = .error
      }
    }
  }
}
protocol WeatherRepository {
protocol WeatherRepository: Actor {
protocol WeatherService {
protocol WeatherService: Actor {
class WAPIWeatherService: WeatherService {
actor WAPIWeatherService: WeatherService {
See forum comments
Download course materials from Github
Previous: Introduction Next: Conclusion