代码之家  ›  专栏  ›  技术社区  ›  Quoc Nguyen Nofan Munawar

尽可能短地将init函数从objective-c转换为swift

  •  0
  • Quoc Nguyen Nofan Munawar  · 技术社区  · 7 年前

    我有一个 init 用Objective-C编写的函数

    Objtovi-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)
    

    我想要什么

    我想找一些提示或其他什么,改变我的目标C代码,使我的快速呼叫尽可能短。( 第一 , 第二 , 第三的 在快速呼叫中) ,像这样

    let callInSwift = MyCustomClassInObjectiveC(1, 2, 3)
    

    let callInSwift = MyCustomClassInObjectiveC(1, and: 2, with: 3)
    
    5 回复  |  直到 6 年前
        1
  •  1
  •   Shehata Gamal    7 年前

    把它改成

    -(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)
    
        2
  •  2
  •   Teetz    7 年前

    第一解决方案:

    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

        3
  •  1
  •   dahiya_boy    7 年前

    改变你 Obj-C码 用下面

    - (instancetype)initWithFirst:(NSInteger)first and: (NSInteger)second with:(NSInteger)third;
    
        4
  •  1
  •   Lal Krishna    7 年前

    你可以使用 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

        5
  •  0
  •   Rakesh Patel    7 年前

    据您所知,如果在方法中使用参数前使用“uuo”,则该参数名称不会在调用时出现。只需要传递值。

    func initWith(_ first: 1, _ andSecond: 2, _ withThird: 3)
    {}