1

I was wondering if this is possible to do in swift and what it would be the way of doing it?

I just want to be able to compare? the scheme of my url to whatever string I want.. This is how I have been doing it in objc.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
        if ([request.URL.scheme isEqual: @"http"] || [request.URL.scheme isEqual:@"https"]) {
            return NO;
        }

    return YES;
} 
John Saunders
  • 160,644
  • 26
  • 247
  • 397
valbu17
  • 4,034
  • 3
  • 30
  • 41
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). BTW, it's "Thanks in advance", not "Thanks in advanced". – John Saunders Feb 11 '15 at 06:44

3 Answers3

1

Use == in Swift instead of isEqual: or isEqualToString: in Objective-C

if (request.URL.scheme == "http" || request.URL.scheme == "https") {
ozz
  • 1,137
  • 7
  • 9
1

Really Swifty:

if let scheme = request.URL.scheme {
    switch scheme {
    case "http", "https":
        return true
    default:
        return false
    }
}

Essentially, safely pull the scheme from the URL (could be nil after all) and then switch on it (which you can do in Swift but not Objective-C) using compound case statements.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
1

The other 2 answers will fail if the source URL doesn't have the scheme in lowercase (i.e., hTTp://…).

Also, the other 2 answers fail to unwrap the optionals (request.URL?.scheme?).

Here's another option:

if let lowercaseScheme = request.URL?.scheme?.lowercaseString {
    if lowercaseScheme.rangeOfString("http") != nil {
        println("It's a match!")
    }
}

Or, in Swift 1.2 (Xcode 6.3):

if let lowercaseScheme = request.URL?.scheme?.lowercaseString where lowercaseScheme.rangeOfString("http") != nil {
    println("It's a match!")
}

Or, if you don't need to actually know the scheme inside the block:

if request.URL?.scheme?.lowercaseString.rangeOfString("http") != nil {
    println("It's a match!")
}

This will match http, https, and hTTpS. It will also match lolHTTProfl. If that's not okay in your use case, use the above answer's approach (the == operator), but with optional unwrapping and lowercaseString.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287