GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Nonisolated function inside SwiftUI struct?

Forums > SwiftUI

Hi, I just had technical interview today with one company. I am junior iOS dev looking to get first iOS dev job and team was super nice to me. They asked me to do super simple app that would parse a data from multiline string, we chatted about an hour, during that time I was asked to move that parsing onto background thread and create a simple UI for it with List etc.

We also talked a bit about actors and isolated and nonisolated context. As they asked me to move that parsing function onto background thread, they asked me to make that function wait a bit before publishing data and asked me to make it async.

Bare in mind during all of this, that parsing function was still part of View struct ContentView. At one point my tech lead asked me to make that function nonisolated, which frankly surprised me. I thought nonisolated and isolated functions are something that is specific to actors. What function does nonisolated keyword have for a function that is part of SwiftUI View?

Here is a code sample. I am interested specifically why loadRecords function should be denoted as nonisolated

//
//  SwiftUIView.swift
//  TestProject
//
//  Created by Štěpán Pazderka on 02.08.2024.
//

import SwiftUI

struct SwiftUIView: View {
    @State var records: [String]

    var body: some View {
        List(records, id: \.self) { record in
            Text(record)
        }
        .task {
            await loadRecords()
        }
    }

    nonisolated func loadRecords() async {
        try? await Task.sleep(for: .seconds(2))
        records = ["Test 1", "Test 2", "Test 3"]
    }
}

#Preview {
    SwiftUIView(records: [])
}

   

You shouldn't mutate the view-isolated records collection from another actor/context. This is the type of code Swift 6 concurrency checking is flagging as a warning, but further down the track it wont compile and will be a full error.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.