1

Having no luck creating a partial range in Swift 4

import Foundation

public extension String {

public var URLScheme: String? {
    guard let schemeRange = self.range(of: "://") else { return nil }
    return self.substring(to: schemeRange.lowerBound)
}

public var URLPortNumber: Int {
    guard let portRange = self.range(of: ":", options: .backwards) else { return -1 }

    let startIndex = self.index(portRange.upperBound, offsetBy: 0)
    let endIndex = self.index(portRange.upperBound, offsetBy: 2)
    guard self[startIndex...endIndex] != "//" else { return -1 }

    return Int(self.substring(from: portRange.upperBound))!
}

public var URLHost: String {
    var host = self

    if let scheme = self.URLScheme {
        host = host.substring(from: self.index(self.startIndex, offsetBy: (scheme + "://").characters.count))
    }

    if let portRange = host.range(of: ":") {
        host = host.substring(to: portRange.lowerBound)
    }

    return host

    }
}

Also after reading the documentation on Substrings, I am still less than clear on their benefit. Has anyone used them for URLs?

Even the syntax is less succinct than dot notation.

1 Answer 1

1

This seems to work!

import Foundation

public extension String {

public var URLScheme: String? {
    guard let schemeRange = self.range(of: "://") else { return nil }
    return String(describing: schemeRange.lowerBound)
}

public var URLPortNumber: Int {
    guard let portRange = self.range(of: ":", options: .backwards) else { return -1 }

    let startIndex = self.index(portRange.upperBound, offsetBy: 0)
    let endIndex = self.index(portRange.upperBound, offsetBy: 2)
    guard self[startIndex...endIndex] != "//" else { return -1 }

    return Int(String(describing: portRange.upperBound))!
}

public var URLHost: String {
    var host = self

    if let scheme = self.URLScheme {
        host = String(describing: self.index(self.startIndex, offsetBy: (scheme + "://").characters.count))
    }

    if let portRange = host.range(of: ":") {
        host = String(describing: portRange.lowerBound)
    }

    return host

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

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.