用于 Swift 的 NSNotFound
Posted
技术标签:
【中文标题】用于 Swift 的 NSNotFound【英文标题】:NSNotFound for Swift 【发布时间】:2015-09-22 01:30:42 【问题描述】:我通过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 选项的用途。如何格式化该行?
【问题讨论】:
【参考方案1】:这只是 C 中结构的 aggregate initialization 语法。您可以改用 NSRange 初始化程序:
let notFoundRange = NSRange(location: NSNotFound, length: 0)
或者,也许更简单:
if linkRange.location != NSNotFound ...
【讨论】:
【参考方案2】:对于那些对这里感兴趣的人来说,使用 jtbandes 答案在 swift 中工作的相同功能。我已经在一堆 URL 上试过了。看起来效果不错..
extension String
func isValidURL() -> Bool
let length:Int = self.characters.count
var err:NSError?
var dataDetector:NSDataDetector? = NSDataDetector()
do
dataDetector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
catch
err = error as NSError
if dataDetector != nil
let range = NSMakeRange(0, length)
let notFoundRange = NSRange(location: NSNotFound, length: 0)
let linkRange = dataDetector?.rangeOfFirstMatchInString(self, options: NSMatchingOptions.init(rawValue: 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
【讨论】:
以上是关于用于 Swift 的 NSNotFound的主要内容,如果未能解决你的问题,请参考以下文章