调用[myFunction]的结果未被使用 [英] Result of call to [myFunction] is unused
问题描述
func makeConstraint(withAnotherView:UIView) - > NSLayoutConstraint
{
//创建一些约束
// ...
//返回创建的约束
return NSLayoutConstraint()
}
如果您只需设置约束并忘记它,可以调用:
[view1 makeConstraint:view2]
稍后存储约束以便您可以删除/修改它,您可以执行以下操作:
NSLayoutConstraint * c;
c = [view1 makeConstraint:view2]
我想在swift中执行此操作,但如果我调用了上面的函数,并没有捕获返回的约束,我得到了警告:
调用'makeConstraint(withAnotherView :)'未使用
非常烦人。有什么办法让Swift知道我并不总是想要捕获返回值?
注意:我知道这一点。这是丑陋的,而不是我要找的:
_ = view1.makeConstraint(withAnotherView:view2)
这是Swift 3中引入的行为。使用 @warn_unused_result
显式注释函数,以便告诉编译器结果应该被调用者使用,现在这是默认行为。
你可以在函数中使用 @discardableResult
属性来通知编译器返回值不必被'消耗'调用者。
@discardableResult
func makeConstraint(withAnotherView:UIView) - > NSLayoutConstraint {
... //做有副作用的事情
return NSLayoutConstraint()
}
view1。 makeConstraint(view2)//无警告
let constraint = view1.makeConstraint(view2)//按预期工作
您可以在演化提案。
In Obj-C, a common practice was to use convenience functions to perform common operations, like configuring auto layout for views:
func makeConstraint(withAnotherView : UIView) -> NSLayoutConstraint
{
// Make some constraint
// ...
// Return the created constraint
return NSLayoutConstraint()
}
If you just needed to set the constraint and forget about it, you could call:
[view1 makeConstraint: view2]
If you wanted to store the constraint later so that you could remove/modify it, you would do something like:
NSLayoutConstraint * c;
c = [view1 makeConstraint: view2]
I want to do this in swift, but if I call the above function and do not capture the returned constraint, I get the warning:
Result of call to 'makeConstraint(withAnotherView:)' is unused
VERY annoying. Is there some way to let Swift know that I don't always want to capture the return value?
NOTE: I know about this. It is ugly and not what I'm looking for:
_ = view1.makeConstraint(withAnotherView: view2)
This is behaviour that has been introduced in Swift 3. Instead of having to explicitly annotate functions with @warn_unused_result
in order to tell the compiler that the result should be used by the caller, this is now the default behaviour.
You can use the @discardableResult
attribute on your function in order to inform the compiler that the return value doesn't have to be 'consumed' by the caller.
@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
You can read about this change in more detail on the evolution proposal.
这篇关于调用[myFunction]的结果未被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!