Objective -C vs. Swift Custom Initializers

时间:2015-05-04 02:08:14

标签: objective-c swift

我正在使用自定义类开发Swift项目。该项目的旧Objective-C版本具有如下所示的自定义init方法。

自定义类的自定义初始化

-(id) initWithURLDictionary: (NSDictionary *) dictionary{
self = [super init]; 
if (self) {
    self.URLDictionary = dictionary;
}
return self;

}

使用此类时,我将使用自定义初始值设定项创建对象,然后将自定义类的委托设置为self。

// Create a temporary dictionary of the feeds, allocate and initialize the FLODataHandler object and set the delegate (me) to self.
NSDictionary *URLTempDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: kFLOCyclingURL, @"FLO Cycling", kTriathleteURL, @"Triathlete", kVeloNewsURL, @"Velo News", kCyclingNewsURL, @"Cycling News", kRoadBikeActionURL, @"Road Bike Action", kIronmanURL, @"Ironman", nil];
self.dataHandler = [[FLODataHandler alloc] initWithURLDictionary: URLTempDictionary];
self.dataHandler.delegate = self;

在Swift中我有点困惑。看来我有两个选择。选项1可以让我在自定义类中创建自定义初始值设定项。

自定义类

中的自定义初始化程序
init(dictionary : [String:String]) { self.URLDictionary = dictionary }

该过程与Objective-C相同。

let URLTempDictionary = [kFLOCyclingURL : "FLO Cycling", kTriathleteURL : "Triathlete", kVeloNewsURL : "Velo News", kCyclingNewsURL : "Cycling News", kRoadBikeActionURL : "Road Bike Action", kIronmanURL : "Ironman"]

    var tempDataHandler = FLODataHandler(dictionary: URLTempDictionary)
    self.dataHandler! = tempDataHandler

选项2不通过投诉,但似乎不完整。

我不会创建自定义初始化程序,而只需执行以下操作。自定义类有一个名为URLDictionary的字典属性。

let URLTempDictionary = [kFLOCyclingURL : "FLO Cycling", kTriathleteURL : "Triathlete", kVeloNewsURL : "Velo News", kCyclingNewsURL : "Cycling News", kRoadBikeActionURL : "Road Bike Action", kIronmanURL : "Ironman"]

self.dataHandler!.URLDictionary = URLTempDictionary
self.dataHandler.delegate = self

所以我的问题与自定义初始化程序的需要和

的使用有关
var tempDataHandler = FLODataHandler(dictionary: URLTempDictionary)

是否使用

self.dataHandler!.URLDictionary = URLTempDictionary

取得同样的结果?

小心,

乔恩

1 个答案:

答案 0 :(得分:1)

初始化程序的目的是有效地强制调用者提供数据 - 而Swift可以通过Objective-C不会执行此合同来帮助您。如果您声明init(dictionary:),则所有其他继承的初始值设定项都将被继承,并且init(dictionary:)将成为唯一方式来创建FLODataHandler。

因此,如果FLODataHandler从get-go中获得URLDictionary值至关重要,那么无论如何都要声明初始值设定项。实际上,如果它也有一个代表是至关重要的,请申报init(dictionary:delegate:)。这是“最佳实践”。

另一方面,关于两阶段初始化没有任何内在的恶意,即首先制作对象,然后给出其属性值;在现实生活中的iOS编程中,有些情况没有真正的替代方案(prepareForSegue会浮现在脑海中)。它的问题在于它依赖于无法执行的合同,呼叫者必须以其他方式简单地知道并自愿遵守。

编辑:你似乎也在问是否只是说

self.dataHandler!.URLDictionary = URLTempDictionary

以某种方式神奇地创建了一个FLODataHandler来占用dataHandler属性。它当然不会。 Swift中没有任何对象神奇地存在,只不过是在Objective-C中。如果没有人说FLODataHandler(...),那么就不存在这样的实例。如果没有人为self.dataHandler分配了一个FLODataHandler实例,则那里没有FLODataHandler(如果这意味着你试图解包nil,上面的代码就会崩溃。)