How to find the first non-repeated character in a string with Swift

1 Answer

0 votes
import Foundation

func getFirstNonRepeatedCharacter(_ s: String) -> Character? {
    for ch in s {
        if s.filter({ $0 == ch }).count == 1 {
            return ch
        }
    }
    return nil
}

if let result = getFirstNonRepeatedCharacter("ppdadxefe") {
    print(result) 
} else {
    print("No unique character found")
}



/*
run:

a

*/

 



answered Jun 28, 2025 by avibootz
...