我在谷歌和 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)
}
}
}
但我总是在以下行中收到错误“Type 'Int' does not conform to protocol 'BooleanType'”:if (chunks.count) {
是什么导致了这个错误? swift 中的其余代码是否正确或是否存在任何其他错误?
最佳答案
chunks.count
的类型为 Int
,但是 if
语句需要一个 boolean 表达式。
这与 (Objective-)C 不同,其中 if 语句的控制表达式可以具有任何标量类型并与零进行比较。
所以对应的Swift代码为
if ([chunks count]) { ... }
是
if chunks.count != 0 { ... }
关于objective-c - 将 Objective-C 转换为 Swift - 错误 : Type 'Int' does not conform to protocol 'BooleanType' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356067/