【问题标题】:How can I initiate an instancetype from Objective-C with Swift如何使用 Swift 从 Objective-C 启动实例类型
【发布时间】:2016-11-30 09:27:03
【问题描述】:

我有一个 api,我必须将它从 Objective-C 翻译成 Swift。 我被某种类型的构造函数或初始化卡住了,我真的不知道。

.h 文件是这样的:

+ (instancetype) newProductionInstance;
+ (instancetype) newDemoInstance;

.m 文件是这样的:

+ (instancetype) newProductionInstance
{
    return [[self alloc] initWithBaseURLString:productionURL];
}

+ (instancetype) newDemoInstance
{
    return [[self alloc] initWithBaseURLString:demoURL];
}

- (instancetype)initWithBaseURLString:(NSString *)urlString
{
    if (self = [self init])
    {
        _apiURL = [NSURL URLWithString:urlString];
    }
    return self;
}

这是他们对我正在翻译的主文件的调用:

mobileApi = [MobileAPI newDemoInstance];

所以我只想将最后一行转换为 Swift 2。

【问题讨论】:

    标签: ios objective-c swift swift2 instancetype


    【解决方案1】:
    var mobileApi = MobileAPI.newDemoInstance()
    

    let mobileApi = MobileAPI.newDemoInstance()
    

    如果你不打算修改它。

    【讨论】:

      【解决方案2】:

      就是MobileAPI.newDemoInstance()

      let mobileApi = MobileAPI.newDemoInstance()
      

      注意:不要忘记在Bridging-Header.h文件中导入MobileAPI.h

      【讨论】:

        【解决方案3】:

        希望对你有帮助

         class YourClass: NSObject {
            //Class level constants
            static let productionURL = "YourProductionURL"
            static let demoURL = "YourDemoURL"
        
            //Class level variable
            var apiURL : String!
        
            //Static factory methods
            static func newProductionInstance() -> YourClass {
                return YourClass(with : YourClass.productionURL)
            }
        
            static func newDemoInstance() -> YourClass {
                return YourClass(with : YourClass.demoURL)
            }
        
            // Init method
            convenience init(with baseURLString : String) {
                self.init()
                self.apiURL = baseURLString
        
                //Calling
                let yourObject : YourClass = YourClass.newDemoInstance()
            }
        }
        

        【讨论】:

        • *with, 应该以小写开头
        【解决方案4】:

        在objective-c 和Swift 中创建实例类型的最佳选择是使用"default" 关键字。此关键字已在 Apple 的标准库中使用。例如 NSNotificationCenter.default 或 NSFileManager.default。要在 .h 文件中声明它,您应该编写

        +(instancetype) default;
        

        在你的 .m 文件中

        static YOUR_CLASS_NAME *instance = nil;
        
        +(instancetype) default {
        if instance == nil { instance = [[super allocWithZone:NULL] init];}
        return instance;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-28
          • 1970-01-01
          相关资源
          最近更新 更多