簡體   English   中英

使用不同數量的輸入數據拆分字符串

[英]Split String with varied amount of input data

我有一個看起來像這樣的字符串:

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

我使用拆分來分隔這些字符串,但我遇到了問題,因為鏈接可能沒有描述或 ID

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

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

當鏈接僅https://product/我收到致命錯誤:索引超出范圍,即使使用選項和字符串插值,我如何保證獨立於鏈接中信息量的代碼不會中斷

您應該檢查路徑組件的數量。 但是,理想情況下,您應該使用URL函數,而不是將鏈接作為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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM