Сначала я настройка: < /p>
struct MySendableType: Sendable {
init() {}
}
class MyNonSendableType {
init() {}
}
func takesSendableParam(closure: (Sendable) -> Void) {
closure(MySendableType())
}
func takesNonSendableParam(closure: (Any) -> Void) {
closure(MyNonSendableType())
}
< /code>
Затем я провожу этот эксперимент: < /p>
func experiment() {
let sendable: (Sendable) -> Void = { data in
// free to pass data across thread boundary since it's sendable.
Task { @MainActor in
DispatchQueue.global().async {
print(data)
DispatchQueue.main.async {
print(data)
}
}
print(data)
}
}
let nonSendable: (Any) -> Void = { data in
// can't pass data across thread boundary since it's not sendable
}
// ...
}
< /code>
Это имеет смысл до сих пор, как я прокомментировал.func experiment() {
let sendable = ...
let nonSendable = ...
// (1) This compiles fine, which makes sense
takesSendableParam(closure: nonSendable)
// (2) Why does this compile fine???
takesNonSendableParam(closure: sendable)
для (2), я ожидаю, что он потерпит неудачу, потому что TakesnonsedableParam передает myNonsendable введите в мою отправку закрытие, а затем отправленное закрытие передает mynonsendable по границе потока. Почему это хорошо компилируется? Я могу подтвердить, что Swift 6 включен. < /P>
Не стесняйтесь играть с полным кодом: < /p>
struct MySendableType: Sendable {
init() {}
}
class MyNonSendableType {
init() {}
}
func takesSendableParam(closure: (Sendable) -> Void) {
closure(MySendableType())
}
func takesNonSendableParam(closure: (Any) -> Void) {
closure(MyNonSendableType())
}
func experiment() {
let sendable: (Sendable) -> Void = { data in
// free to pass data around since it's sendable.
Task { @MainActor in
DispatchQueue.global().async {
print(data)
DispatchQueue.main.async {
print(data)
}
}
print(data)
}
}
let nonSendable: (Any) -> Void = { data in
}
takesSendableParam(closure: nonSendable)
// Why does this compiles fine???
takesNonSendableParam(closure: sendable)
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... in-swift-6