andyPaul andyPaul - 1 year ago 98
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 Source
let result = userNames.filter { $0.lowercased().characters.prefix(2).contains("e") }

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

This should do it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download