2016-06-21 58 views
14

在的OBJ-C,常见的做法是使用的方便功能,执行常见的操作,如配置视图自动布局:结果调用[myFunction的]的未使用

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

    // Return the created constraint 
    return NSLayoutConstraint() 
} 

如果你只需要设置约束和忘掉它,你可以拨打:

[view1 makeConstraint: view2]

如果你想存储的限制后,这样你可以删除/修改它,你会做这样的事情:

NSLayoutConstraint * c; 
c = [view1 makeConstraint: view2] 

我想这样做是迅速的,但如果我把上面的功能和不捕获返回的约束,我得到警告:

Result of call to 'makeConstraint(withAnotherView:)' is unused 

很烦人。有什么方法让Swift知道我并不总是想捕获返回值?

注:我知道这一点。这是丑陋的,而不是什么我在寻找:

_ = view1.makeConstraint(withAnotherView: view2) 

回答

24

这是Swift 3中引入的行为,而不是必须使用@warn_unused_result明确注释函数来告诉编译器结果应该被调用者使用,现在这是默认行为。

您可以在函数中使用@discardableResult属性,以通知编译器返回值不必由调用方'消耗'。

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

    ... // do things that have side effects 

    return NSLayoutConstraint() 
} 

view1.makeConstraint(view2) // No warning 

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

您可以了解这种变化上更详细the evolution proposal

+0

一方面你可以把@discardableResult一次并修复它们,但另一方面你不能与你的豆荚一起。所以你在函数调用前加上_ =来忽略结果 –

相关问题