Swift 什么是__“消费”;你喜欢斯威夫特吗?

Swift 什么是__“消费”;你喜欢斯威夫特吗?,swift,Swift,在中有一些函数前面加了\uuuu(很可能还有其他地方,但我还没有仔细看过)。我知道它是某种类型的声明修饰符,但我不确定它是做什么的。它是由宏定义的: 据我所知,\u消费实际上还没有做任何事情。它是在预期的实现中添加的,此时将使用它来表示使用它所调用的值的方法(即,该值将从调用者移动到被调用者) 说明,考虑这个伪代码: // Foo is a move-only type, it cannot be copied. moveonly struct Foo { consuming func ba

在中有一些函数前面加了
\uuuu
(很可能还有其他地方,但我还没有仔细看过)。我知道它是某种类型的声明修饰符,但我不确定它是做什么的。

它是由宏定义的:


据我所知,
\u消费
实际上还没有做任何事情。它是在预期的实现中添加的,此时将使用它来表示使用它所调用的值的方法(即,该值将从调用者移动到被调用者)

说明,考虑这个伪代码:

// 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`.
该属性当前以两个下划线作为前缀,以指示用户在实际实现仅移动类型之前不应使用该属性,此时该属性可能会重命名为
消费

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

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

在仅移动类型的实现之前添加属性的原因是为了准备Swift 5 ABI稳定性冻结,论坛将对此进行更详细的讨论:


请参见。因此,它被添加为序列和收集函数的标记,以表明它们最终将支持仅移动类型?这就是我的理解,但我不是这方面的专家。
// 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`.