bioche
(Eric Blachère)
1
I'm currently exploring Concurrency in order to better prepare for stricter errors in Swift 6. To do this I enabled strict concurrency check on my swift package and I encountered a behaviour that seems odd to me with Sendable methods.
Consider the following code :
class Foo {
var fooInt: Int = 0
@Sendable
func doSomethingNotThreadSafe() {
fooInt = fooInt + 1
}
func callTask1() {
Task { doSomethingNotThreadSafe() } // <-- Warning : Capture of 'self' with non-sendable type 'Foo' in a `@Sendable` closure
}
func callTask2() {
let doSomethingNotThreadSafe = doSomethingNotThreadSafe
Task { doSomethingNotThreadSafe() }
}
}
We do get a proper warning in callTask1 but we don't get a warning in callTask2 because doSomethingNotThreadSafe is marked @Sendable which feels like a hack to bypass thread-safety checks.
So I wonder if it's expected to be able to use @Sendable on methods that are inside structs or classes. I understand its necessity for closures & nested functions but in other cases it could lead to data races it seems.
Or maybe change the name to @uncheckedSendable in that case to alert that the compiler is not checking much here.
I'm curious about your thoughts on this 
1 Like
0xTim
(Tim)
2
@Sendable on functions is counter intuitive and IMO I'm shocked it was ever actually implemented that way - all it does is disable sendable checking on the function - it doesn't actually make it Sendable or do anything safe. There is no work around for what you're trying to do, it's reliant on SE-0418 to fix the warning.
(Confusingly you can use a closure instead and mark that as @Sendable and that works as expected)
2 Likes
bioche
(Eric Blachère)
3
Thank you for this answer, I hadn't notice this in the proposal earlier ! If I understand it correctly, point 5 of the detailed design of the proposal will disallow @Sendable on functions of non-Sendable types which is exactly what bugged me here ^^
As you say it's currently quite unsafe.