Home > database >  How to use swift's firstIndex to generate a new subarray?
How to use swift's firstIndex to generate a new subarray?

Time:02-17

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

CodePudding user response:

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

  • Related