简体   繁体   English

如何使用swift的firstIndex生成新的子数组?

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

For example, I have array let candidates=["1","0","a","b","c"] , and I want to return ["a","b","c"]例如,我有数组let candidates=["1","0","a","b","c"] ,我想返回["a","b","c"]

Here's the code:这是代码:

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

But got error: No 'subscript' candidates produce the expected contextual result type '[String]'但出现错误: No 'subscript' candidates produce the expected contextual result type '[String]'

Does your function expect to return type [String] ?您的 function 是否期望返回类型[String]

candidates[head..<candidates.count] will return type ArraySlice so if you want to convert that to an array , you might need to do candidates[head..<candidates.count]将返回类型ArraySlice所以如果你想把它转换成一个array ,你可能需要做

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

One more small addition for completeness, since you want to return ["a","b","c"] , you will need to start from the index after "0" so I would do:为了完整性再增加一点,因为你想返回["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