gpt4 book ai didi

ios - 用于 Swift 的 NSNotFound

转载 作者:行者123 更新时间:2023-11-28 09:58:44 25 4
gpt4 key购买 nike

我通过 Antony 找到了这个解决方案用于验证 URL。

- (BOOL)isValidURL {
NSUInteger length = [self length];
// Empty strings should return NO
if (length > 0) {
NSError *error = nil;
NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
if (dataDetector && !error) {
NSRange range = NSMakeRange(0, length);
NSRange notFoundRange = (NSRange){NSNotFound, 0};
NSRange linkRange = [dataDetector rangeOfFirstMatchInString:self options:0 range:range];
if (!NSEqualRanges(notFoundRange, linkRange) && NSEqualRanges(range, linkRange)) {
return YES;
}
}
else {
NSLog(@"Could not create link data detector: %@ %@", [error localizedDescription], [error userInfo]);
}
}
return NO;
}

我想尝试一下,但我正在快速编码。这是我目前所拥有的。

extension String{
func isValidURL() -> Bool{
let length:Int = self.characters.count
var err:NSError? = nil
let dataDetector:NSDataDetector?
do{
dataDetector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
}catch{
err = error as? NSError
}
if dataDetector != nil && err != nil{
let range = NSMakeRange(0, length)
let notFoundRange = (NSRange){ NSNotFound, 0 } //How do I format this for swift?
let linkRange = dataDetector?.rangeOfFirstMatchInString(self, options: 0, range: range)
if !NSEqualRanges(notFoundRange, linkRange) && NSEqualRanges(range, linkRange){
return true
}
}else{
print("Could not create link data detector: \(err?.localizedDescription): \(err?.userInfo)")
}

return false
}
}

绊脚石是 NSNotFound。据我所知,这就是 swift optionals 的用途。如何格式化该行?

最佳答案

就是aggregate initialization C 中结构的语法。您可以改用 NSRange 初始值设定项:

let notFoundRange = NSRange(location: NSNotFound, length: 0)

或者,也许更简单:

if linkRange.location != NSNotFound { ...

关于ios - 用于 Swift 的 NSNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706998/

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