我正在将此Java代码转换为swift:
for (int i = 0 ; i < groups.length ; i++) {
try {
groups[i] = integerPart.substring (i * 3, i * 3 + 3);
} catch (IndexOutOfBoundsException ex) {
groups[i] = integerPart.substring (i * 3);
}
groups[i] = new StringBuilder (groups[i]).reverse ().toString ();
groups[i] = get1To3DigitString (groups[i]) + " " + getTheWord (i) + " ";
}
注:
integerPart
是字符串。groups
是字符串数组。请忽略
get1To3DigitString
和getTheWord
。我的想法和尝试:
由于swift的字符串非常烦人(不能用
Int
索引),我决定使用NSString
的substringFromIndex
和substringWithRange
方法来执行substring
Java方法。所以我写了这两个方法来帮助我:func substring (s: String, start: Int, end: Int) throws -> String{
let ns = NSString(string: s)
return String(ns.substringWithRange(NSRange(start..<end)))
}
func substring (s: String, start: Int) -> String {
let ns = NSString(string: s)
return String(ns.substringFromIndex(start))
}
我知道
NSString
中的两个子字符串方法抛出一个NSRangeException
,就像Java的IndexOutOfBoundsException
。这是我的swift代码:for var i = 0 ; i < groups.count ; i++ {
do {
try groups[i] = substring(integerPart, start: i * 3, end: i * 3 + 3)
} catch NSRangeException {
groups[i] = substring(integerPart, start: i * 3)
}
groups[i] = String (groups[i].characters.reverse())
groups[i] = get1To3DigitString (groups[i]) + " " + getTheWord (i) + " "
}
我得到一个错误,说捕获模式不匹配!我认为它确实匹配,因为如果不匹配,我应该如何捕获异常?所以我删除了这个词。
我想如果在
ErrorType
中抛出异常,我会在ErrorType
部分捕获它。但是当我测试它时,在NSRangeException
行出现了一个异常!我想这是因为我写的捕捉模式不正确。我该如何捕捉
substring
? 最佳答案
就像在Java
中,你永远不会捕捉到IndexOutOfBoundsException
一样,你永远不会在Swift或Objective-C中捕捉到NSRangeException
。
这些异常是因为你作为开发人员搞砸了,而不是应用程序或一些外部因素,或者用户输入了他的信息。在Java
中,术语checked exceptions和unchecked exceptions。第一个你可以,也应该,甚至必须捕捉,第二个发生在运行时,信号主要是程序中的错误。
在字符串的第十个字符之前,不能对子字符串的长度为5的字符串进行子串操作,这是开发人员可以而且必须知道的。如果你这样做,程序应该会崩溃。
我不确定你是否真的能抓住一个NSRangeException
-如果你做不到我会很高兴。对于常规错误,可以定义自定义错误类型:
enum LevelParsingException : ErrorType {
case MalformedJson
case InvalidLevelContent
}
然后你有一些函数可以抛出它们:
func parseLevel() throws {
guard someCondition {
throw LevelParsingException.InvalidLevelContent
}
}
然后调用该方法并捕获可能出现的所有不同错误:
func call() {
do {
try parseLevel()
} catch LevelParsingException.InvalidLevelContent {
print("something")
} catch {
print("something else")
}
}
apple docs解释得比较好。