swift 中 NSRangeException 的错误句柄

Error Handle of NSRangeException in swift

我在 objective 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

Total data length(sourceData.length) should be maximum from your staring point(4000) and length of data(20) which you need to retrieve

guard sourceData.length >= (4000 + 20) else{

   throw LevelParsingException.InvalidLevelContent
}