When #objc and #nonobjc write before method and variable in swift? - ios

When I declare static parameter in extension of class then I have to write #nonobjc before variable like:
#nonobjc static let test = "test"
and sometimes I have to write #objc before method, so what is use of #objc and #nonobjc in Swift.
Can anyone help me for this problem?

This is explained in the Apple's official documentation about Objective-C - Swift interoperability:
When you use the #objc(name) attribute on a Swift class, the class is
made available in Objective-C without any namespacing. As a result,
this attribute can also be useful when migrating an archivable
Objective-C class to Swift. Because archived objects store the name of
their class in the archive, you should use the #objc(name) attribute
to specify the same name as your Objective-C class so that older
archives can be unarchived by your new Swift class.
Conversely, Swift also provides the #nonobjc attribute, which makes a
Swift declaration unavailable in Objective-C. You can use it to
resolve circularity for bridging methods and to allow overloading of
methods for classes imported by Objective-C. If an Objective-C method
is overridden by a Swift method that cannot be represented in
Objective-C, such as by specifying a parameter to be a variable, that
method must be marked #nonobjc.
To summarize, use #objc when you want to expose a Swift attribute to Objective-C without a namespace . Use #nonobjc if you want to keep the attribute available and accessible only in Swift code.

(Addendum/additional official details to #bontoJR well summarizing answer)
From the Swift Language Reference - Attributes [emphasis mine]:
objc
Apply this attribute to any declaration that can be represented in
Objective-C — for example, non-nested classes, protocols, nongeneric
enumerations (constrained to integer raw-value types), properties and
methods (including getters and setters) of classes and protocols,
initializers, deinitializers, and subscripts. The objc attribute tells
the compiler that a declaration is available to use in Objective-C
code.
...
nonobjc
Apply this attribute to a method, property, subscript, or initializer
declaration to suppress an implicit objc attribute. The nonobjc
attribute tells the compiler to make the declaration unavailable in
Objective-C code, even though it is possible to represent it in
Objective-C.
...

Here you can find more details in this Swift Documentation : InteractingWithObjective-C
As an answer of your question, overview from attached link is as below.
#objc : You can use attribute to change the name of a class, property, method, enumeration type, or enumeration case declaration in
your interface as it’s exposed to Objective-C code.
Example : if the name of your Swift class contains a character that isn’t supported by Objective-C, you can provide an alternative name to use in Objective-C.
#nonobjc : It makes a swift declaration unavailable in Objective-C. You can use it to resolve circularity for bridging
methods and to allow overloading of methods for classes imported by
Objective-C.

Related

Tell Swift compiler method as swift only

I have a swift class defined like this:
#objcMembers
public class MyURL: NSObject {
func concat(_ components: String...) -> MyURL {
concat(components)
}
/// Concat the specified components one by one.
func concat(_ components: [String]) -> MyURL {
components.forEach { let _ = value?.appendingPathComponent($0) }
return self
}
// All the other methods which are available for objc.
}
There are many methods inside which are available for objective-c, so I use the #objcMembers for class prefix directly, then swift compiler starts to complaint this:
Method 'concat' with Objective-C selector 'concat:' conflicts with previous declaration with the same Objective-C selector
They are exactly have the same function signature, but the latter one is only available for swift even if exposed. Now I'm looking for some compile flags to mark the latter concat method as swift only to tell the compiler to ignore the conflict error.
#objc and #objcMembers do that explicitly, so how to do it reverse?
https://docs.swift.org/swift-book/ReferenceManual/Attributes.html#nonobjc
“nonobjc
Apply this attribute to a method, property, subscript, or initializer declaration to suppress an implicit objc attribute. 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.
Applying this attribute to an extension has the same effect as applying it to every member of that extension that isn’t explicitly marked with the objc attribute.
You use the nonobjc attribute to resolve circularity for bridging methods in a class marked with the objc attribute, and to allow overloading of methods and initializers in a class marked with the objc attribute.
A method marked with the nonobjc attribute can’t override a method marked with the objc attribute. However, a method marked with the objc attribute can override a method marked with the nonobjc attribute. Similarly, a method marked with the nonobjc attribute can’t satisfy a protocol requirement for a method marked with the objc attribute.”

Question about Importing Swift code into objective c code

I read this documentation for importing swift code into objective c.
https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c
I have a few questions.
Can I put #objc annotation for a Struct?
Do I need to inherit all the class that I want to export to obj to be child of NSobject ? I am getting error 'error: only classes that inherit from NSObject can be declared #objc'
When I export a swift class with #objc, I need to add #objc to all its parent classes, protocol and interface and also class and structure in all its methods, is that correct?
No. Objective-C cannot see a native Swift struct.
Yes. Objective-C classes must basically be derived from NSObject. Objective-C can be made aware of the existence of other classes, but it cannot do anything useful with them.
You can mark the class with #objcMembers, in which case you will give everything within it full visibility to Objective-C.

Extending generic objective c class in swift class

So I am slowly adding more swift files to codebase.
Suppose I have class in Objective c:
ListData<Type : CSJSONData *> : ServerData <CSListData>
I want to subclass it in swift class like this:
#objc class ArticlesData: ListData<Article>
Compiler gives me error:
Generic subclasses of '#objc' classes cannot have an explicit '#objc' because they are not directly visible from Objective-C
Replace '#objc ' with ''
But I need to have it #objc to keep available in my objc part of code ! How to do it ?
From The Swift Programming Language (4.2), Attributes:
The compiler implicitly adds the objc attribute to subclasses of any class defined in Objective-C. However, the subclass must not be generic, and must not inherit from any generic classes. You can explicitly add the objc attribute to a subclass that meets these criteria, to specify its Objective-C name as discussed below.
Unfortunately for you this is pretty definitive.

Accessing Swift Class Public Variable in Objective-C Class Xcode 9

I am trying to access Public variable in Objective-C class declared in swift class. But I am getting "Unknown Method" error. Here is my code for accessing variable:
NSLog(#"job on quick blox : %#",[QuickBloxJobClass jobOnQB]);
and it shows compile error:
No known class method for selector 'jobOnQB'
And here is my code in QuickBloxJobClass:
#objc public class QuickBloxJobClass: NSObject
{
static var jobOnQB: QBCOCustomObject = QBCOCustomObject ()
}
I cannot make it public variable because I have Class methods in QuickBloxJobClass. Even I tried it by creating a variable for QuickBloxJobClass. But the variable was still unaccessible.
It was working working fine in Xcode .
Please suggest me some solution.
I'm not sure why jobOnQB cannot be public, presence of class methods should not interfere with it being public, but if it cannot be public for some reason, you can add a static method to QuickBloxJobClass to get the variable.
BTW, the syntax [QuickBloxJobClass jobOnQB] is for calling a static method jobOnQB on class QuickBloxJobClass (it works, though). Strictly speaking, however, since jobOnQB is a property, a better Objective-C syntax would be QuickBloxJobClass.jobOnQB.
Another observation is that #objc inference is deprecated in Swift 4, so it's a good idea to explicitly mark Swift methods and properties callable from Swift with #objc. In fact, you have to do it if Swift 3 #objc inference is set to Off.
Update: This needs to be further investigated, it may be just a matter of some settings. I get the behavior you described if I add Swift code to a project initially set up as Objective-C, but internal members defined in Swift can be accessed just fine in Objective-C if the project is initially set up in Swift with Objective-C files added later. Again, if Swift 3 #objc inference is disabled, you still have to mark such members with #objc.
Update 2: This access problem can be resolved in a project initially set up in Objective-C by adding a bridging header. Then internal Swift members become visible in Objective-C, even though the purpose of a bridging header is the opposite: make Objective-C stuff visible in Swift.

Objective-C call Swift function

Swift function defined in MySwift.swift File:
func SomeSwift()
{
}
SomeSwift() is not defined in any Swift class, it is just a pure function.
After CMD + B to build the project, open Project-Swift.h, the SomeSwift() isn't show in there.
Does the function in Swift have to be defined in some Swift class? and with #objc marked?
like the following:
#objc class SomeSwift: NSObject {
func SomeSwift()
{
}
}
Referring to Apple Documentation about Using Swift from Objective-C:
A Swift class must be a descendant of an Objective-C class to be
accessible and usable in Objective-C
Means that your class should be #objc class SomeSwift: NSObject (You're right!), but you CANNOT access the whole thing in Swift file:
When you create a Swift class that descends from an Objective-C class,
the class and its members—properties, methods, subscripts, and
initializers—that are compatible with Objective-C are automatically
available from Objective-C. This excludes Swift-only features, such as
those listed here:
Generics
Tuples
Enumerations defined in Swift without Int raw value type
Structures defined in Swift
Top-level functions defined in Swift
Global variables defined in Swift
Typealiases defined in Swift
Swift-style variadics
Nested types
Curried functions
Reference.
So, you cannot use the SomeSwift top-level function.
Even if you tried to add #objc before its declaration, the compiler will tell that:
#objc can only used when with memebers of classes, #objc protocols,
and concrete extensions of classes.
with a suggestion to remove #objc.

Resources