Swift startsWith method?

use hasPrefix instead of startsWith.

Example:

"hello dolly".hasPrefix("hello")  // This will return true
"hello dolly".hasPrefix("abc")    // This will return false

here is a Swift extension implementation of startsWith:

extension String {

  func startsWith(string: String) -> Bool {

    guard let range = rangeOfString(string, options:[.AnchoredSearch, .CaseInsensitiveSearch]) else {
      return false
    }

    return range.startIndex == startIndex
  }

}

Example usage:

var str = "Hello, playground"

let matches    = str.startsWith("hello") //true
let no_matches = str.startsWith("playground") //false

Edit: updated for Swift 3.

The Swift String class does have the case-sensitive method hasPrefix(), but if you want a case-insensitive search you can use the NSString method range(of:options:).

Note: By default, the NSString methods are not available, but if you import Foundation they are.

So:

import Foundation
var city = "San Antonio"
var searchString = "san "
let range = city.range(of: searchString, options:.caseInsensitive)
if let range = range {
    print("San Antonio starts with san at \(range.startIndex)");
}

The options can be given as either .caseInsensitive or [.caseInsensitive]. You would use the second if you wanted to use additional options, such as:

let range = city.range(of: searchString, options:[.caseInsensitive, .backwards])

This approach also has the advantage of being able to use other options with the search, such as .diacriticInsensitive searches. The same result cannot be achieved simply by using . lowercased() on the strings.


To answer specifically case insensitive prefix matching:

in pure Swift (recommended most of the time)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return lowercased().hasPrefix(prefix.lowercased())
    }
}

or:

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return lowercased().starts(with: prefix.lowercased())
    }
}

note: for an empty prefix "" both implementations will return true

using Foundation range(of:options:)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return range(of: prefix, options: [.anchored, .caseInsensitive]) != nil
    }
}

note: for an empty prefix "" it will return false

and being ugly with a regex (I've seen it...)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        guard let expression = try? NSRegularExpression(pattern: "\(prefix)", options: [.caseInsensitive, .ignoreMetacharacters]) else {
            return false
        }
        return expression.firstMatch(in: self, options: .anchored, range: NSRange(location: 0, length: characters.count)) != nil
    }
}

note: for an empty prefix "" it will return false

Tags:

Ios

Swift