gpt4 book ai didi

ios - swift 中 NSRangeException 的错误处理

转载 作者:行者123 更新时间:2023-11-30 11:44:30 24 4
gpt4 key购买 nike

我在 Objective C 中使用 try catch block 进行了尝试。这段代码运行良好

    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 block 尝试它时,它没有给出异常错误并且应用程序当时崩溃了。

 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 错误。

最佳答案

最后我达到了以下解决方案,如果需要快速处理范围异常,那么我们需要这样做

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
}

关于ios - swift 中 NSRangeException 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com