在Objective-C中为swift类使用多参数init的语法

时间:2017-06-07 21:24:35

标签: ios objective-c swift language-interoperability

我是一名新的iOS开发人员,我在项目中的单独目标C文件中初始化Swift类时遇到了一个小问题。我已经正确配置了项目并根据这个问题的答案导入了类:

Can't use Swift classes inside Objective-C

我的问题是:在Objective-C中调用此swift类的init方法的语法是什么?

@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)
    }
}

我试过这样写:

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];

其中book是NSDictionary

但是有一个错误“'Book'没有可见的@interface'声明选择器'initWithNewTitle:newAuthor:NewDetail:.....'

1 个答案:

答案 0 :(得分:1)

所有参数都需要与Objective-C兼容。您必须使用所有@objc类,并且只使用Objective-C支持的数据类型。例如,元组和Swift结构在Objective-C中不是有效类型。

我认为Optionals不受支持。你的init方法是可选的。我很确定这是你的问题。