2025-02-11 09:32:51
,某些文章具有时效性,若有错误或已失效,请在下方留言。Any properties and methods that belong to an actor are isolated to that actor, but you can make external functions isolated to an actor if you want. This allows the function to access actor-isolated state as if it were inside that actor, without needing to use await
.
属于某个 actor 的任何属性和方法都与该actor隔离,但如果需要,可以将外部 函数与该actor隔离。这允许函数访问 actor 隔离的状态,就像它位于该 actor 内部一样,而无需使用 await
。
Here’s a simple example so you can see what I mean:
这里有一个简单的例子,这样你就能明白我的意思了:
actor DataStore {
var username = "Anonymous"
var friends = [String]()
var highScores = [Int]()
var favorites = Set<Int>()
init() {
// load data here
}
func save() {
// save data here
}
}
func debugLog(dataStore: isolated DataStore) {
print("Username: \(dataStore.username)")
print("Friends: \(dataStore.friends)")
print("High scores: \(dataStore.highScores)")
print("Favorites: \(dataStore.favorites)")
}
let data = DataStore()
await debugLog(dataStore: data)
That creates a DataStore
actor with various properties plus a couple of placeholder methods, then creates a debugLog()
function that prints those without using await
– they can be accessed directly.
这将创建一个具有各种属性和几个占位符方法的 DataStore
actor,然后创建一个 debugLog()
函数,该函数无需使用 await
即可打印这些 – 可以直接访问它们。
Notice the addition of the isolated
keyword in the function signature; that’s what allows this direct access, and it even allows the function to write to those properties too.
请注意在函数签名中添加的 isolated
关键字;这就是允许这种直接访问的原因,它甚至允许函数也写入这些属性。
Using isolated
like this does not bypass any of the underlying safety or implementation of actors – there can still only be one thread accessing the actor at any one time. What we’ve done just pushes that access out by a level, because now the whole function must be run on that actor rather than just individual lines inside it. In practice, this means debugLog(dataStore:)
needs to be called using await
.
像这样使用 isolated
不会绕过 actor 的任何底层安全或实现 —— 任何时候仍然只能有一个线程访问 actor。我们所做的只是将该访问权限推出一个级别,因为现在整个函数必须在该 actor 上运行,而不仅仅是其中的单个行。实际上,这意味着需要使用 await
调用 debugLog(dataStore:)
。
This approach has an important side effect: because the whole function is now isolated to the actor, it must be called using await
even though it isn’t marked as async. This makes the function itself a single potential suspension point rather than individual accesses to the actor being suspension points.
这种方法有一个重要的副作用:因为整个函数现在与 actor 隔离,所以必须使用 await
调用它,即使它没有被标记为 async。这使得函数本身成为单个潜在的暂停点,而不是对 actor 的单独访问成为暂停点。
In case you were wondering, you can’t have two isolation parameters, because it wouldn’t really make sense – which one is executing the function?
如果您想知道,您不能有两个隔离参数,因为它没有意义 – 哪个参数正在执行函数?