Skip to content

Instantly share code, notes, and snippets.

@Maxim-Kolmogorov
Last active August 27, 2023 17:57
Show Gist options
  • Save Maxim-Kolmogorov/72436e3b8800ecec7dcc6cecc766e1e9 to your computer and use it in GitHub Desktop.
Save Maxim-Kolmogorov/72436e3b8800ecec7dcc6cecc766e1e9 to your computer and use it in GitHub Desktop.
Phone input mask on swift.
extension String {
func formatUserInput(pattern: String) -> String {
var inputCollection = Array(self)
var resultCollection: Array<Character> = []
for i in 0 ..< pattern.count {
let patternCharIndex = String.Index(utf16Offset: i, in: pattern)
let patternChar = pattern[patternCharIndex]
guard let nextInputChar = inputCollection.first else { break }
if (patternChar == nextInputChar || patternChar == "#") {
resultCollection.append(nextInputChar)
inputCollection.removeFirst()
} else {
resultCollection.append(patternChar)
}
}
return String(resultCollection)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment