Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access an actor from within a filter closure

I’m having trouble working out how to access an actor from a filter closure. Take this example code:

import Foundation

actor MyActor {
    var contents: [String]
    
    init() {
        self.contents = []
    }
}


let myActor = MyActor()
let list: [String] = []

Task {
    list.filter { item in myActor.contents.contains { $0 == item } }
}

I get the syntax error: Actor-isolated property 'contents' can not be referenced from a non-isolated context. Which makes sense, but I just cannot work out how to provide the correct syntax.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Put the actor’s contents in a local let constant first, then use that local constant in filter:

Task {
    let actorContents = await myActor.contents
    let result = list.filter { item in actorContents.contains { $0 == item } }
}

You wouldn’t want filter to use the updated myActor.contents halfway through, if myActor.contents changes at some point during the filtering, right? Therefore, make a local copy of it first, and use that.

Also, consider using a Set for better efficiency:

let actorContents = Set(await myActor.contents)
let result = list.filter { item in actorContents.contains(item) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading