什么"__consuming"在Swift中做什么?

Dal*_*ney 17 swift

__consumingSequence.swift中有一些函数(很可能是其他地方,但我还没有真正环顾四周).我知道它是某种类型的声明修饰符,但我不确定它是做什么的.

Ham*_*ish 22

据我了解,__consuming它实际上并没有做任何事情.它是在预期实现仅移动类型的情况下添加的,此时它将用于表示消耗调用它的值的方法(即,值将从调用者移动到被调用者).

为了说明,请考虑这个伪代码:

// Foo is a move-only type, it cannot be copied.
moveonly struct Foo {
  consuming func bar() { // Method is marked consuming, therefore `self` is moved into it.
    print(self) // We now 'own' `self`, and it will be deinitialised at the end of the call.
  }
}

let f = Foo()
f.bar() // `bar` is a `consuming` method, so `f` is moved from the caller to the callee.
print(f) // Invalid, because we no longer own `f`.
Run Code Online (Sandbox Code Playgroud)

该属性当前以两个下划线为前缀,以指示在实际实现仅移动类型之前,用户不应使用该属性,此时可能会将其重命名为consuming.

正如您所知,已经标记__consuming了一些标准库协议要求,以表明它们可以通过仅移动类型的消费方法以及非消费方法来满足.这与mutating协议要求表明它可以通过mutating值类型的方法或其他非变异方法满足的方式大致相同(但据我所知,没有实际的编译器逻辑支持检查的__consuming还).

例如,filter(_:)要求Sequence已被标记为消耗,因为采用仅移动元素的序列将需要能够将适用的元素移动到结果数组中,从而使序列无效.

在实现仅移动类型之前添加属性的原因是为Swift 5 ABI稳定性冻结做准备.正如马丁所说,这在论坛上有更详细的讨论: