1

I am trying to use this class

REDActionSheet.h

I've imported it into my bridging header and everything. I have other Objective C class as well. XCode seems to detect the class and I could initialize it normally.

However, Swift does not seem to recognize the constructor for this class

Here is how it is initialized in Objective C

REDActionSheet *actionSheet = [[REDActionSheet alloc] initWithCancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitlesList:@"1", @"2", @"3", nil];

But when I try to use it in Swift. Swift does not recognize the Constructor. For other libraries, Swift seem to be intelligent enough to detect the Constructor. The XCode code completion does not seem to detect the constructor as well

I can only initialize it like this.

var actionSheet: REDActionSheet = RedActionSheet();

Normally XCode would be intelligent enough to give me the Constructor like this

var actionSheet: REDActionSheet = REDActionSheet(cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitlesList: ["1", "2", "3"], nil);

But for this class, it doesnt seem to be the case

Since I have no experience in Objective C. I have no idea what makes Swift to recognize the Objective C Constructor

Any idea please?

Darren
  • 25,520
  • 5
  • 61
  • 71
JayVDiyk
  • 4,277
  • 22
  • 70
  • 135

2 Answers2

1

The problem is that the initializer is a variadic Obj-C method, which won't be automatically imported into Swift.

This answer describes how you can expose a C variadic method to Swift.

If that's a little much, you could create a small Obj-C extension that takes a fixed number of arguments:

MyExtension.h

@interface REDActionSheet (MyExtension)
- (instancetype)initWithCancelButtonTitle:(NSString*)cancelButtonTitle
                   destructiveButtonTitle:(NSString*)destructiveButtonTitle
                         otherButtonTitle:(NSString*)otherButtonTitle;
@end

MyExtension.m

@implementation REDActionSheet (MyExtension)

- (instancetype)initWithCancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitle:(NSString*)otherButtonTitle
{
    return [self initWithCancelButtonTitle:cancelButtonTitle
                    destructiveButtonTitle:destructiveButtonTitle
                     otherButtonTitlesList:otherButtonTitle, nil];
}

@end
Community
  • 1
  • 1
Darren
  • 25,520
  • 5
  • 61
  • 71
0

The last argument is a varargs, not a list, so use:

var actionSheet: REDActionSheet = REDActionSheet(cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitlesList: "1", "2", "3", nil);
David Berry
  • 40,941
  • 12
  • 84
  • 95