Swift 调用[myFunction]的结果未使用

Swift 调用[myFunction]的结果未使用,swift,function,Swift,Function,在Obj-C中,一种常见做法是使用便利功能执行常见操作,如配置视图的自动布局: func makeConstraint(withAnotherView : UIView) -> NSLayoutConstraint { // Make some constraint // ... // Return the created constraint return NSLayoutConstraint() } 如果只需要设置约束并忘记它,可以调用: [view1-m

在Obj-C中,一种常见做法是使用便利功能执行常见操作,如配置视图的自动布局:

func makeConstraint(withAnotherView : UIView) -> NSLayoutConstraint
{
   // Make some constraint 
   // ...

   // Return the created constraint
   return NSLayoutConstraint()
}
如果只需要设置约束并忘记它,可以调用:

[view1-makeConstraint:view2]

如果希望稍后存储约束以便删除/修改它,可以执行以下操作:

NSLayoutConstraint * c;
c = [view1 makeConstraint: view2]
我想在swift中执行此操作,但如果调用上述函数但未捕获返回的约束,则会收到警告:

Result of call to 'makeConstraint(withAnotherView:)' is unused
很烦人。有没有办法让斯威夫特知道我并不总是想获取返回值

注:我知道这一点。它很难看,不是我想要的:

_ = view1.makeConstraint(withAnotherView: view2)

您可以尝试从项目的生成设置中关闭警告。我喜欢这个问题,说得好。做了一些研究,发现了这一点


尚未对其进行测试。

这是Swift 3中引入的行为。为了告诉编译器调用者应该使用结果,不必显式地用
@warn\u unused\u result
注释函数,这现在是默认行为

您可以在函数上使用
@discardablesult
属性来通知编译器返回值不必被调用方“使用”

@discardableResult
func makeConstraint(withAnotherView : UIView) -> NSLayoutConstraint {

   ... // do things that have side effects

   return NSLayoutConstraint()
}


您可以在上更详细地了解此更改。

一方面,您可以放置@discardableResult一次,然后将其全部修复,但另一方面,您无法使用播客完成此更改。因此,您可以通过在函数调用前面添加=来忽略结果
view1.makeConstraint(view2) // No warning

let constraint = view1.makeConstraint(view2) // Works as expected