我在目标c中尝试使用try catch block.It正常使用此代码
NSString *string = @"This is demo text";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//it's(data) length is 17
@try {
NSData *subdata = [data subdataWithRange:NSMakeRange(4000, 20)];
} @catch (NSException *exception) {
NSLog(@"exception ERROR: %@",exception);
}
这是打印异常错误。
但是当我在swift中尝试使用try catch块时,它没有给出异常错误,并且应用程序崩溃了。
var sourceString = "This is demo text"
let sourceData = sourceString.data(using: String.Encoding.utf8)! // sourceData is equivalent to "wav" from question
guard let subdata = Data(sourceData.subdata(in: 4000 ..< (4000 + 20))) else{
throw LevelParsingException.InvalidLevelContent
}
我试图在swift 3中处理NSRangeException错误。
最后我达到了以下解决方案:如果需要处理范围异常,那么在swift中我们需要这样做
var sourceString = "This is demo text"
let sourceData = sourceString.data(using: String.Encoding.utf8)! // sourceData is equivalent to "wav" from question
总数据长度(源Data.length)应该是您需要检索的起点(4000)和数据长度(20)的最大值
guard sourceData.length >= (4000 + 20) else{
throw LevelParsingException.InvalidLevelContent
}