I am sure this is a simple question, but I cant see how to solve it.
I am storing an array of my actors in an Array. I need to get access to some of its value in a .first( where:{} )
call. Here is a short example of what I want to do:
actor Counter{
var number:Int
init(number: Int) {
self.number = number
}
func getNumber()->Int{
return number
}
}
var counters:[Counter] = []
func addCounter(){
for i in 1...10 {
let counter = Counter(number: i )
counters.append( counter )
}
}
func getCounter2( number:Int )->Counter?{
let found = counters.first { counter in
return counter.number == number //--error: Actor-isolated property 'number' can not be referenced from a nonisolated context
}
return found
}
Thanks for your help
You are fetching actor isolated property, and you simply cannot do that from a synchronous context. This is easily solved if you make getCounter2
an async
method. Are you open to that?
func getCounter2(number: Int) async -> Counter? {
for counter in counters {
if await counter.number == number {
return counter
}
}
return nil
}
If you cannot support an asynchronous pattern like this, you may have to consider a significantly more dramatic refactoring of the problem.