Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the ObjC version of @discardableResult declaration in Swift

In Swift 3, there will be a warning when return value didn't used. The @discardableResult declaration will suppress the feature.

How do I declare this in ObjC files, means, the opposite of __attribute__((warn_unused_result))

like image 324
leavez Avatar asked Nov 01 '16 04:11

leavez


People also ask

What is @discardableresult in IOS Swift?

The discardable result attribute allows you to use the return value if you want while you can decide as well to just ignore it. This keeps your code clean and removes any related warnings in your project.

What is the use of @objc in Swift?

That's where the @objc attribute comes in: when you apply it to a class or method it instructs Swift to make those things available to Objective-C as well as Swift code.

What is @nonobjc?

The nonobjc attribute tells the compiler to make the declaration unavailable in Objective-C code, even though it's possible to represent it in Objective-C.

What is @objcMembers?

If you want all the methods and properties to be available for Objective-C, you can use the @objcMembers attribute. 1 2 3 4 5 6. @objcMembers class SomeClass { func doSomething() { print("hello!") } } In that way, it will be available to the objective-c code without adding @objc specifically to the methods.


1 Answers

Ignoring the return value of a function is by default in ObjC and for Swift < 3.

No warning will occur if you don't capture what the method returned. But from swift 3 onwards you must use the return value and if you don't want, use @discardable result attribute to the method.

In ObjC, if you want to warn you can use warn_unused_result attribute.

-(int) mymethod : (int) a __attribute__((warn_unused_result)){

    return  2;

}

- (BOOL)doSomething  {

    return 2;
}



[self doSomething];
[self mymethod:2];//warning:ignoring return value of a function
like image 51
Anish Parajuli 웃 Avatar answered Sep 24 '22 00:09

Anish Parajuli 웃