Sequence.swift中有__consuming
开头的函数(很可能也在其他地方,但是我并没有真正环顾四周)。我知道这是某种类型的声明修饰符,但我不确定它的作用。
答案 0 :(得分:15)
据我了解,__consuming
实际上还没有做任何事情。它是为预期move-only types的实现而添加的,这时将使用它来表示消费所调用值的方法(即该值将从呼叫者转移到被呼叫者)。
为说明起见,请考虑以下伪代码:
// 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
。
您已经发现,一些标准库协议要求have been marked __consuming
是为了表明它们可以通过仅移动类型的使用方法以及非使用方法来满足。这与mutating
协议要求表明可以通过值类型的mutating
方法或其他非变异方法(但据我所知)可以满足的方式几乎相同我知道,尚无实际的编译器逻辑支持对__consuming
的检查。)
例如,对filter(_:)
的{{1}}要求已被标记为消耗,因为采用仅移动元素的序列需要能够将适用的元素移动到结果数组中,从而使之无效顺序。
之所以在仅移动类型的实现之前就已经添加属性,是为了为Swift 5 ABI稳定性冻结做准备。 As Martin says,这将在论坛上进行详细讨论:
答案 1 :(得分:3)