使用Switch语句将Swift便利init转换为Objective-C

时间:2016-04-12 14:55:42

标签: objective-c swift switch-statement nsrange

我正在尝试将此快速代码转换为Objective-C

convenience init(fromString string: String, format:DateFormat)
    {
        if string.isEmpty {
            self.init()
            return
        }

        let string = string as NSString

        switch format {

        case .DotNet:

            let startIndex = string.rangeOfString("(").location + 1
            let endIndex = string.rangeOfString(")").location
            let range = NSRange(location: startIndex, length: endIndex-startIndex)
            let milliseconds = (string.substringWithRange(range) as NSString).longLongValue
            let interval = NSTimeInterval(milliseconds / 1000)
            self.init(timeIntervalSince1970: interval)

到目前为止,我这样做了:

-(id) initFromString: (NSString *) string format: (DateFormat *) format{
    if (string == nil) {
        self = [self init];
        return self;
    }


    switch (format) {
        case .DotNet:
            NSRange *startIndex = [[string rangeOfString:@"("] location]+1;

    }
}

并且已经遇到以下错误:

表示switch(format):语句需要表达整数类型(DateFormat * __strong'无效)

以及以下两行:预期表达式

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

在Objective-C中,字符串是隐含的可选项。对nil的测试仅测试是否提供了字符串。它不检查是否提供了空字符串。您可能希望切换到string.length == 0,因为通过nil-messaging的魔力,它可以检查空字符串或根本没有字符串。

Objective-C使用C的switch语句。因此,您只能打开整数类型。如果这最初是Objective-C代码,DateFormat可能是NS_ENUM - 整数类型而不是对象类型。看起来原始版本是使用点语法的枚举?如果你可以使它成为Objective-C枚举,那么只需使用:

- (id)initFromString:(NSString *)string format:(DateFormat)format {
    ....
    switch(format)
    {
        case DateFormatDotNet: {
            ....
        } break;
    }

case中的花括号是因为你想在那里声明变量。)

否则,如果它必须是对象格式,那么你正在看一个痛苦的结构,如:

if([format isEqual:[DateFormat dotNetFormat]]) {
}
else if([format isEqual:[DateFormat otherFormat]]) {
}
... etc ...

此外,Objective-C在struct之间有一个句法上的区别,它们正是它们在C语言中的命名字段但没有内置行为 - 和对象类型,这又是因为它是一个严格的超集C. NSRange是一个结构。因此方括号消息传递语法不起作用。而不是:

[[string rangeOfString:@"("] location]

使用:

[string rangeOfString:@"("].location

rangeOfString调用周围的方括号,因为它是对对象的消息调度,然后是位置的点,因为您将C结构作为值返回,这就是人们如何访问C结构中的字段。

(点语法也适用于Objective-C对象的属性,但明确地用于getter和setter调用的别名,仅适用于最新的Objective-C三十年)

答案 1 :(得分:0)

假设此代码与How to convert a Swift enum: String into an Objective-C enum: NSString?

相关

由于您的DateFormat变量是一个dateFormatType为NSString的对象,因此您将不得不使用链式if-else结构从各种可能性中进行选择:

if([format.dateFormatType compare: DotNetDateFormatType] == NSOrderedSame) {
    [self handleDotNetDateFormat: format]
} else if ([format.dateFormatType compare: RSSDateFormatType] == NSOrderedSame) {
   [self handleRSSDateFormat: format]
...

Objective-C没有关于枚举值的点值语法的概念(所以" .DotNet"不是Objective-C中的有效术语)。这就是编译器抱怨这两行的原因。