简体   繁体   中英

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"]

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]'

Does your function expect to return type [String] ?

candidates[head..<candidates.count] will return type ArraySlice so if you want to convert that to an array , you might need to do

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM