Accessing class member in swift

204 views
Skip to first unread message

JulienD

unread,
Jun 18, 2017, 2:32:47 PM6/18/17
to j2objc-discuss
Hello,

Providing this class:

class MyClass {
   int value;
}


j2objc generates something like this (extract):

@interface MyClass {
 @public
  jint value_;
}

With this implementation myClass.value_ is unaccessible in an easy way in swift (according to
https://stackoverflow.com/questions/26082999/accessing-objective-c-base-classs-instance-variables-from-a-swift-class )

I found that the @Property annotation will do the job like this:

class MyClass {
   @Property
   int value;
}

after generation:
@interface MyClass {

}
 @property jint value;

However, it may be a big work to add this annotation everywhere in the code.

My question is :
As it seems to be the only way to access members by swift, is there a particular reason
for which public members in java classes are not automatically declared @properties when using
the --swift-friendly flag?


I'm pretty new on iOS dev, so I may say some mistakes....

BTW, j2objc is a F.... awesome cool project! Nice job.  ;)

Regards
Julien


Tom Ball

unread,
Jun 18, 2017, 3:01:02 PM6/18/17
to j2objc-discuss
Use j2objc's --swift-friendly flag. It defines class accessor methods for static variables (which should address this problem), so the Swift importer recognizes them, and enables nullability annotations to reduce Swift warnings. If you only want accessor methods, though, use the --static-accessor-methods flag instead.

--
You received this message because you are subscribed to the Google Groups "j2objc-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to j2objc-discus...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

JulienD

unread,
Jun 18, 2017, 4:13:57 PM6/18/17
to j2objc-discuss
I'm already using --swift-friendly but I'm not speaking about static variable. In my example, value is an instance variable not a static one.

Tom Ball

unread,
Jun 19, 2017, 3:20:44 AM6/19/17
to j2objc-discuss
Is it public? Only public accessors are declared in the header file, which is what the Swift importer reads.

JulienD

unread,
Jun 19, 2017, 10:40:03 AM6/19/17
to j2objc-discuss
This class with a public variable:

class MyClass {
   public int value;
}

generates an objective-C class whicih works pretty well when called by another objective-C class. However
when called by a swift class, the variable "value" is unreachable because it is declared as an instance variable
and not as a proerty.

Keith Stanger

unread,
Jun 19, 2017, 10:49:26 AM6/19/17
to j2objc-discuss
Since the general best practice in Java is to keep instance members private and make them accessible via getter and setter methods this hasn't previously been an issue. Since public instance fields should be relatively rare, is using @Property really too cumbersome?
Reply all
Reply to author
Forward
0 new messages