Last active
August 27, 2023 17:57
-
-
Save Maxim-Kolmogorov/72436e3b8800ecec7dcc6cecc766e1e9 to your computer and use it in GitHub Desktop.
Phone input mask on swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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