2015-09-22 51 views
0

我的驗證網址,發現該解決方案通過AntonyNSNotFound爲斯威夫特

- (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。至於我可以告訴大家這是迅速自選是。如何格式化行?

回答

4

它只是aggregate initialization語法爲C.結構可以使用NSRange初始化,而不是:

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

或者更簡單地說:

if linkRange.location != NSNotFound { ... 
1

對於那些有興趣在這裏是一樣的功能使用jtbandes回答迅速工作。我已經試過了上一堆網址。似乎工作很好..

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 
    } 
}