【问题标题】:Translating Objective-C to Swift - Error: Type 'Int' does not conform to protocol 'BooleanType'将 Objective-C 转换为 Swift - 错误:类型“Int”不符合协议“BooleanType”
【发布时间】:2015-02-05 23:52:30
【问题描述】:

我在 google 和 SO 上进行了搜索,但没有找到任何有关此问题的有用帮助。 我正在尝试将此代码从 Objective-c 转换为 swift:

- (void)metaTitleUpdated:(NSString *)title {
NSLog(@"delegate title updated to %@", title);

NSArray *chunks = [title componentsSeparatedByString:@";"];
if ([chunks count]) {
    NSArray *streamTitle = [[chunks objectAtIndex:0] componentsSeparatedByString:@"="];
    if ([streamTitle count] > 1) {
        titleLabel.text = [streamTitle objectAtIndex:1];
    }
}
}

到目前为止,我已将其翻译成这样:

func metaTitleUpdated(input: String) {
    println("delegate title updated to \(title)")

    let chunks: NSArray = title!.componentsSeparatedByString(";")
    if (chunks.count) {
        let streamTitle = chunks .objectAtIndex(0) .componentsSeparatedByString(";")
        if (streamTitle.count > 1) {
        titleLabel.text = streamTitle.objectAtIndex(1)
        }
    }

}    

但我总是在以下行中收到错误“类型'Int'不符合协议'BooleanType'”:if (chunks.count) {

是什么导致了这个错误? swift中的其余代码是否正确或是否有任何其他错误?

【问题讨论】:

    标签: objective-c swift methods nsstring boolean


    【解决方案1】:

    chunks.count 的类型为 Int,但 if 语句需要布尔表达式。 这与 (Objective-)C 不同,其中 if 语句的控制表达式可以具有任何标量类型并与零进行比较。

    所以对应的Swift代码为

    if ([chunks count]) { ... }
    

    if chunks.count != 0 { ... }
    

    【讨论】:

    • 你的意思是chunks.count > 0? :)
    • @GuyKogus:哎呀,是的。谢谢!
    • 解决了这个错误,谢谢。但现在我收到一个错误:“[AnyObject]”在“titleLabel.text = streamTitle.objectAtIndex(1)”行没有名为“objectAtIndex”的成员,这有什么问题?
    • @EnnioE.Meier:这意味着 streamTitle 是一个 Swift 数组而不是 NSArray。您可以尝试let streamTitle : NSArray = ...,就像您对块定义所做的那样。或者,使用 Swift 数组索引。
    • 我现在把代码改成了这样: func metaTitleUpdated(input: String) { println("delegate title updated to (title)") let chunks: NSArray = title!.componentsSeparatedByString(";") if chunks.count != 0 { let StreamTitle: NSArray = chunks .objectAtIndex(0) .componentsSeparatedByString("=") if (StreamTitle.count > 1) { titleLabel.text! = StreamTitle.objectAtIndex(1) as NSString } } } 但我在运行时收到错误消息“致命错误:在展开可选值时意外发现 nil”
    【解决方案2】:

    我自己解决了答案。

    func metaTitleUpdated(title: String) {
        var StreamTitle = split(title) {$0 == "="}
        var derRichtigeTitel: String = StreamTitle[1]
      titleLabel.text = derRichtigeTitel
        println("delegate title updated to \(derRichtigeTitel)")
    }
    

    【讨论】:

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