Created
August 19, 2016 17:43
-
-
Save jancassio/dd69a25c040a02a3b798dd0cec29965a to your computer and use it in GitHub Desktop.
Simple string formatter based on mask string
This file contains hidden or 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
// | |
// StringMask.swift | |
// StringMask | |
// | |
// Created by Jan Cássio on 8/19/16. | |
// Copyright © 2016 Jan Cassio. All rights reserved. | |
// | |
import Foundation | |
enum StringMaskr { | |
case CPF | |
case Phone | |
func mask () -> String { | |
switch self { | |
case .CPF: | |
return "***.***.***-**" | |
case .Phone: | |
return "(**) *****-****" | |
} | |
} | |
func placeholder () -> String { | |
return "*" | |
} | |
} | |
extension String { | |
func formatWithMask (mask stringMask: StringMaskr) -> String { | |
let mask = stringMask.mask() | |
let placeholderChar = stringMask.placeholder() | |
var result = "" | |
if self.characters.count > 0 { | |
let tempString = self.makeOnlyDigitsString() | |
var formatterIndex = mask.startIndex | |
var tempIndex = tempString.startIndex | |
var stop = false | |
while !stop { | |
let formatterRange = formatterIndex..<formatterIndex.advancedBy(1) | |
let currentChar = "\(mask.substringWithRange(formatterRange))" | |
if currentChar != placeholderChar { | |
result += currentChar | |
} | |
else if tempString.characters.count > 0 { | |
let stringRange = tempIndex..<tempIndex.advancedBy(1) | |
result += tempString.substringWithRange(stringRange) | |
tempIndex = tempIndex.advancedBy(1) | |
} | |
formatterIndex = formatterIndex.advancedBy(1) | |
stop = formatterIndex >= mask.endIndex || tempIndex >= tempString.endIndex | |
} | |
} | |
return result | |
} | |
func makeOnlyDigitsString() -> String { | |
return self.componentsSeparatedByCharactersInSet( | |
NSCharacterSet.decimalDigitCharacterSet().invertedSet | |
).joinWithSeparator("") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment