0
我的驗證網址,發現該解決方案通過Antony。NSNotFound爲斯威夫特
- (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;
}
我想試試它,但我在swift中編碼。 這是我到目前爲止。
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。至於我可以告訴大家這是迅速自選是。如何格式化行?