What should be the return type of range: range or NSRange?

I am using swift 4 and this code snippet throws me an error while initialising n1 variable:

 func caseInsensitiveSearch(searchString: String) -> NSRange?  {
        if let range = self.range(of: searchString, options: .caseInsensitive),
            let n1 = NSRange(range, in: self) {
                return n1
        }
        return nil
    }

Can I pass pass directly the Range? or it is necessary to convert it in to NSRange.

Any idea??

1 answer

  • answered 2018-04-17 05:10 RomOne

    It's because you are trying to unbind a non optional value, you can directly return it like so:

    func caseInsensitiveSearch(searchString: String) -> NSRange?  {
            if let range = self.range(of: searchString, options: .caseInsensitive) {
                    return  NSRange(range, in: self)
            }
            return nil
        }