我有一个用Objective-C编写的init
函数
Objective-C
@interface MyCustomClassInObjectiveC: NSObject
- (instancetype)initWithFirst:(NSInteger)first AndSecond: (NSInteger)second withThird:(NSInteger)third;
@end
当我在Swift中调用它时,它会显示所有first
,second
,third
快速
let callInSwift = MyCustomClassInObjectiveC(first: 1, andSecond: 2, withThird: 3)
我想要的
我想找到一些提示或其他内容,这些提示会更改我的Objective-C代码以使我的Swift调用尽可能短(否first
,second
,{{1} },例如
third
或
let callInSwift = MyCustomClassInObjectiveC(1, 2, 3)
答案 0 :(得分:2)
第一个解决方案:
class MyCustomClassInSwift: NSObject {
init(_ first: Int, _ second: Int, _ third: Int) {
// do your stuff
}
}
您可以这样称呼:
let myCustomObject = MyCustomClassInSwift(1, 2, 3)
第二个解决方案:
class MySecondCustomClassInSwift: NSObject {
init(_ first: Int, and second: Int, with third: Int) {
// do your stuff
}
}
您可以这样调用第二个解决方案:
let mySecondCustomObject = MySecondCustomClassInSwift(1, and: 2, with: 3)
护理:如果要使用import Foundation
NSObject
答案 1 :(得分:1)
在下面更改 obj-c代码
- (instancetype)initWithFirst:(NSInteger)first and: (NSInteger)second with:(NSInteger)third;
答案 2 :(得分:1)
将其更改为
-(instancetype)init:(NSInteger)first :(NSInteger)second :(NSInteger)third;
通话将如下
let callInSwift = MyCustomClassInObjectiveC(1, 2, 3)
//
其他选择
-(instancetype)init:(NSInteger)first and: (NSInteger)second with:(NSInteger)third;
因此您可以使用
let callInSwift = MyCustomClassInObjectiveC(1, and: 2, with: 3)
答案 3 :(得分:1)
您可以使用NS_SWIFT_NAME
宏。
- (instancetype)initWithFirst:(NSInteger)first AndSecond: (NSInteger)second withThird:(NSInteger)third
NS_SWIFT_NAME(init(first:second:third:));
这可以称为:
MyCustomClassInObjectiveC(first: 1, second: 2, thrid: 3)
有关更多信息,请阅读:Advanced ObjC <-> Swift Interoperability
答案 4 :(得分:0)
据您所知,如果您在方法中的参数前使用'_',则该参数名称不会在调用时出现。仅值需要通过。
func initWith(_ first: 1, _ andSecond: 2, _ withThird: 3)
{}