簡體   English   中英

如何使用swift的firstIndex生成新的子數組?

[英]How to use swift's firstIndex to generate a new subarray?

例如,我有數組let candidates=["1","0","a","b","c"] ,我想返回["a","b","c"]

這是代碼:

if let head = candidates.firstIndex(of: "0") {
    return candidates[head..<candidates.count]
}

但出現錯誤: No 'subscript' candidates produce the expected contextual result type '[String]'

您的 function 是否期望返回類型[String]

candidates[head..<candidates.count]將返回類型ArraySlice所以如果你想把它轉換成一個array ,你可能需要做

return Array(candidates[head..<candidates.count])

為了完整性再增加一點,因為你想返回["a","b","c"] ,你需要從“0”之后的索引開始,所以我會這樣做:

return Array(candidates[head+1..<candidates.count])

暫無
暫無

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

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