2017-09-20 3 views
1

pas avoir de chance de créer une plage partielle à Swift 4mal à convertir aux opérateurs sous-chaînes partiel Swift Range 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 

    } 
} 

également après avoir lu le documentation sur sous-chaînes, je suis encore moins clair sur leur avantage. Quelqu'un les a-t-il utilisés pour les URL?

Même la syntaxe est moins succincte que la notation par points.

Répondre

1

Cela semble fonctionner!

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 

    } 
}