15

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)
GoldenJoe
  • 7,874
  • 7
  • 53
  • 92

2 Answers2

29

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.

Hamish
  • 78,605
  • 19
  • 187
  • 280
  • On one hand you can put @discardableResult once and fix them all, but on other hand you can't make it with you pods. So you Ignore the result by adding _ = in front of the function call – New-Learner Nov 17 '17 at 05:52
0

You can try to turn the warnings off from the Build Settings of your project. I like the question, good point. Done some research and found this. https://stackoverflow.com/a/34932152/5615274

Did not test it yet.

Community
  • 1
  • 1
robertsan
  • 1,591
  • 3
  • 14
  • 26