Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading