Generic Function

withUnsafeCurrentTask(body:)

Calls a closure with an unsafe reference to the current task.

Declaration 宣言

func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T

Parameters パラメータ

body

A closure that takes an UnsafeCurrentTask parameter. If body has a return value, that value is also used as the return value for the withUnsafeCurrentTask(body:) function. あるクロージャ、それはUnsafeCurrentTaskバラメータを取ります。bodyが戻り値を持つならば、その値はまたwithUnsafeCurrentTask(body:)関数の戻り値としても使われます。

Return Value 戻り値

The return value, if any, of the body closure. bodyクロージャの、もしあれば、戻り値。

Discussion 解説

If you call this function from the body of an asynchronous function, the unsafe task handle passed to the closure is always non-nil because an asynchronous function always runs in the context of a task. However, if you call this function from the body of a synchronous function, and that function isn’t executing in the context of any task, the unsafe task handle is nil.

Don’t store an unsafe task reference for use outside this method’s closure. Storing an unsafe reference doesn’t affect the task’s actual life cycle, and the behavior of accessing an unsafe task reference outside of the withUnsafeCurrentTask(body:) method’s closure isn’t defined. Instead, use the task property of UnsafeCurrentTask to access an instance of Task that you can store long-term and interact with outside of the closure body. 代わりに、UnsafeCurrentTasktaskプロパティを使うことで、あなたが長期間格納することそしてクロージャ本体の外側で相互作用することが可能なTaskのインスタンスにアクセスしてください。