Xcode 13 b5
I am trying to mock/stub an actor. However, I'm running into issues. Is it possible for an actor to conform to a protocol? For example, if we have the following Protocol and actor, the compiler complains that Actor-isolated instance method 'fetchProduct(id:)' cannot be used to satisfy a protocol requirement
protocol ProductFetcher: AnyObject {
func fetchProduct(id: String) async -> Product
}
actor ProductStore: ProductFetcher {
private var cache: [String: Product] = [:]
func fetchProduct(id: String) -> Product {
if let product = cache[id] {
return product
}
let newProduct = Product(id: "1111", name: "New Product")
cache[id] = newProduct
return newProduct
}
}
A few suggested fixes pop up
Add '@asyncHandler' to function 'fetchProduct(id:)' to create an implicit asynchronous context
Add 'nonisolated' to 'fetchProduct(id:)' to make this instance method not isolated to the actor
but I don't know to use the suggested fixes
Additionally, I tried passing in the function instead of a protocol. Like so
typealias ProductFetcher = (String) async -> Product
class MyViewModel {
private let productFetcher: ProductFetcher
init(productFetcher: @escaping ProductFetcher) {
self.productFetcher = productFetcher
}
func load(id: String) async {
let product = await productFetcher(id)
print(product)
}
}
let viewModel = MyViewModel(productFetcher: ProductStore.fetchProduct)
However, I get
Cannot convert value of type '(isolated ProductStore) -> (String) -> Product' to expected argument type 'ProductFetcher' (aka '(String) async -> Product')
So, how can I mock an actor?