swiftstringstring-interpolationswift-optionals

Split String with varied amount of input data


I have a string that looks like this:

https://product/000000/product-name-type-color

I used a split to separate this strings, but Im having problems because the link can come without the description or the id

guard let separateLink = deeplink?.split(separator: "/") else { return }

let linkWithoutProductDetails = "\(separateLink[0] ?? "")//\(separateLink[1] ?? "")/\(separateLink[2] ?? "")"

When the link comes only https://product/ Im getting Fatal error: Index out of range even using the Optionals and String Interpolation, how can i guarantee that independently of the quantity of informations in my link the code wont break


Solution

  • You should check the number of path components. However, ideally you should use the URL functions instead of manipulating the link as a String:

    if var url = URL(string: "https://product/000000/product-name-type-color") {
        let pathComponents = url.pathComponents
    
        // "product" is not a path component, it's the host.
        // Path components are "/", "000000" and "product-name-type-color"
        if pathComponents.count > 2 {
            url = url.deletingLastPathComponent()
        }
    
        print(url)
    }