4

I created a URL Validation function that validates for URL as text is entered by a user into a text field.

However, in an effort to save performance and memory, I want to ignore entries that may contain common URL prefixes:

(i.e. http://, http://www, www, etc)

With that said, I want to be able to "smartly" ignore text that may MATCH one of these URL prefixes:

["http://www", "https://www", "www"]
i.e. If a user has typed "htt", it should be ignored since it is a substring of "http://www" or "https://www"

What is the best way to check if a string may match provided prefixes but not necessarily are equal?

1

3 Answers 3

2

From the Swift Programming Language Guide, you can use the hasPrefix method.

Example:

if userString.hasPrefix("http") {
    // do something with userString
}

Source: Swift Programming Language Guide

Sign up to request clarification or add additional context in comments.

1 Comment

That only matches the whole string. Doesn't match partial strings. I figured it out, see below answer.
0

Ok, figured it out. Had to use 'rangeOfString' function and check if user's text was in my control text.

Code:

    let prefixes = ["http://www.", "https://www.", "www."]
    for prefix in prefixes
    {
        if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
            completion(success: false, urlString: nil, error: "Url String was prefix only")
            return
        }
    }

Comments

0

a simple partial comparison can be achieved by using .contains

let string = "hello Swift"
if string.contains("Swift") {
    print("exists")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.