【发布时间】:2014-07-24 13:07:49
【问题描述】:
我开始学习 Swift 并希望找到它作为 Objective C 的绝佳替代品。
我正在尝试将我的 Objective C 类转换为 Swift,但我找不到将以下方法转换为 Swift 的最佳方法。
@implementation VersionReader
- (NSString *)readVersionFromString:(NSString *)string {
if (string.length == 0) {
return nil;
}
unichar firstChar = [string characterAtIndex:0];
if (firstChar < '0' || firstChar > '9') {
return nil;
}
NSUInteger length = string.length;
for (NSUInteger i = 0; i < length; ++i) {
if ([string characterAtIndex:i] == ' ') {
return [string substringToIndex:i];
}
}
return string;
}
@end
到目前为止,我的 Swift 代码如下所示:
import Cocoa
class VersionReader {
func readVersionFromString(string: String) -> String? {
if (string.isEmpty) {
return nil
}
var firstChar = string.characterAtIndex[0]
if (firstChar < 48 || firstChar > 57) {
return nil
}
var length = string.utf16Count
for (var i = 0; i < length; ++i) {
if (string.characterAtIndex(i) == 32) {
return string.substringToIndex(i)
}
}
return string
}
}
Tom this,我在两行得到同样的错误:
'String' does not have a member named 'characterAtIndex'
在 Swift 中进行这项工作的替代方法是什么?提前致谢。
【问题讨论】:
-
IMO 苹果没有在 Swift 中提供 characterAtIndex 是有原因的。主要问题是角色是什么并不是一个容易回答的问题。对于初学者,有代理对和平面 1 字符,它们是两个 UTF-16 代码点。表情符号字符在平面 1 中。另请注意,出于同样的原因,没有 String.length 方法。
-
'characterAtIndex` 和
length在NSString中存在同样的问题,看来Apple 已经决定解决方案是不提供无法按预期工作的方法。 'length' 被utf16count和countElements替换,后者是一种迭代字符串的方法,用 O(N) 时间计算字符数。 -
您期望什么输入字符串以及您想要生成什么输出?我倾向于相信整个方法可以改进。
标签: objective-c swift