簡體   English   中英

如何使用 Swift 從 Objective-C 啟動實例類型

[英]How can I initiate an instancetype from Objective-C with Swift

我有一個 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。

var mobileApi = MobileAPI.newDemoInstance()

let mobileApi = MobileAPI.newDemoInstance()

如果你不打算修改它。

它只是MobileAPI.newDemoInstance()

let mobileApi = MobileAPI.newDemoInstance()

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

我希望這會有所幫助

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

在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM