有一些函数前缀为__consuming
in 序列.swift https://github.com/apple/swift/blob/master/stdlib/public/core/Sequence.swift(很可能其他地方也有,但我还没有真正环顾四周)。我知道这是某种类型的声明修饰符,但我不确定它的作用。
据我了解,__consuming
实际上还没有做任何事情。它是在预计实施时添加的仅移动类型 https://github.com/apple/swift/blob/master/docs/OwnershipManifesto.md#non-copyable-types,此时它将用于表示一个方法consumes它被调用的值(即该值将从调用者移动到被调用者)。
为了说明这一点,请考虑以下伪代码:
// 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`.
该属性当前以两个下划线为前缀,以指示用户在实际实现仅移动类型之前不应使用它,此时它可能会被重命名为consuming
.
正如您所发现的,一些标准库协议要求已被标记__consuming https://github.com/apple/swift/pull/16894以表明它们可以通过仅移动类型的消耗方法以及非消耗方法来满足。这与mutating
协议要求表明它可以通过mutating
值类型上的方法,或其他非变异方法(但据我所知,没有实际的编译器逻辑支持检查__consuming
yet).
例如,filter(_:)
要求Sequence
已被标记为消耗,因为采用仅移动元素的序列需要能够将适用的元素移动到结果数组中,从而使序列无效。
之所以在仅移动类型实现之前添加该属性,是为了为 Swift 5 ABI 稳定性冻结做准备。正如马丁所说 https://stackoverflow.com/questions/51292799/what-does-consuming-do-in-swift#comment89563468_51292799,这在论坛上有更详细的讨论:
- 为仅移动类型准备迭代 ABI https://forums.swift.org/t/preparing-the-iteration-abi-for-move-only-types/12980
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)