Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift startsWith method?

Tags:

ios

swift

People also ask

What is startsWith method?

The startsWith() method of String class is used for checking prefix of a String. It returns a boolean value true or false based on whether the given string begins with the specified letter or word. For example: String str = "Hello"; //This will return true because string str starts with "He" str.

How do you check if a string starts with a substring in Swift?

To check if a String str1 starts with another String str2 in Swift, use String. starts() function. Call starts() function on str1 and pass str2 as argument. starts() function returns a boolean value.

What type of value is return by startsWith () method?

Returns: A boolean value: true - if the string starts with the specified character(s)

Is startsWith () case sensitive?

startsWith method is case sensitive.


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

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


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.