andyPaul andyPaul - 28 days ago 8
Swift Question

Swift rangeOfString index 0 or 1

I have a array of Names and want to filter out those which has first OR second letter as "E", from the following array

var userNames = ["John","Tom","Ed","Ben","Albert"]


The outputShould be ["Ed","Ben"]. Albert should not be included as the position is not from 1st or second

let filteredNames = userName.filter { (inputStr) -> Bool in

if let inputRang = inputStr.range(of: "e", options: .caseInsensitive, range: nil, locale: nil)
{
//How do I check the position 0 or 1 here

return true
}
return false
}

Answer
let result = userNames.filter { $0.lowercased().characters.prefix(2).contains("e") }

print(result) // ["Ed", "Ben"]

This should do it.

Comments