Last active
May 23, 2017 15:49
-
-
Save dbonates/01819b30a956e756ff89765f72b56d57 to your computer and use it in GitHub Desktop.
Extension to extract handy substrings from a String. Ex.: credit card number masks. Returns empty string if you abuse it :P
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
| import Foundation | |
| extension String { | |
| public func tailString(from offset: Int) -> String { | |
| return offset > -1 ? "" : self.substring( | |
| from: self.index(self.endIndex, | |
| offsetBy: abs(offset) > characters.count ? -characters.count : offset) | |
| ) | |
| } | |
| public func leadString(until offset: Int) -> String { | |
| return offset < 0 ? "" : self.substring( | |
| to: self.index(self.startIndex, | |
| offsetBy: abs(offset) > characters.count ? characters.count : offset) | |
| ) | |
| } | |
| } | |
| let maskedNum = "4185xxxxxxxx9024" | |
| let lastDigits = maskedNum.tailString(from: -4) // output: "9024" | |
| let leadDigits = maskedNum.leadString(until: 4) // output: "4185" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment