0

I am a new iOS developer and am having a small problem initializing a Swift class in a separate objective C file within my project. I have already configured the project properly and imported the class as per answers to this question:

Can't use Swift classes inside Objective-C

My question is this: what would be the syntax to call the init method of this swift class in objective-C?

@objc class Book: NSObject{
    private var title: String
    private var author: String
    private var detail: String
    private var buyLink: String
    private var rank: integer_t
    private var lastRank: integer_t?

    public init(newTitle: String,newAuthor: String, newDetail: String, newBuyLink: String, newRank: integer_t, newLastRank: integer_t?){
        self.title = newTitle
        self.author = newAuthor
        self.detail = newDetail
        self.buyLink = newBuyLink
        self.rank = newRank
        self.lastRank = newLastRank
    }

    func getBasicInfo() -> (title: String, author: String) {
        return (title, author)
    }

    func getDetailInfo() -> (detail: String, buyLink: String, rank: integer_t, lastRank: integer_t?) {
        return (detail, buyLink, rank, lastRank)
    }
}

I have tried writing it like so:

NSString *title = [NSString stringWithFormat:@"%@", book[@"title"]];
NSString *author = [NSString stringWithFormat:@"%@", book[@"author"]];
NSString *detail = [NSString stringWithFormat:@"%@", book[@"description"]];
NSString *buyLink = [NSString stringWithFormat:@"%@", book[@"amazon_product_url"]];
int rank = [book[@"rank"] intValue];
int lastRank = [book[@"rank_last_week"] intValue];

Book *bookFromList = [[Book alloc] initWithNewTitle: title newAuthor: author 
    newDetail: detail newBuyLink: buyLink newRank: rank newLastRank: lastRank];

where book is a NSDictionary

but there is an error "No visible @interface for 'Book' declares the selector 'initWithNewTitle:newAuthor:NewDetail:.....'

Ben
  • 3
  • 4

1 Answers1

1

All the parameters need to be compatible with Objective-C. You have to use all @objc classes, and only data types that are supported by Objective-C. Tuples and Swift Structs, for example, are not valid types in Objective-C.

I don't think Optionals are supported. You're init method takes an optional. I'm pretty sure that's your problem.

Duncan C
  • 115,063
  • 19
  • 151
  • 241