Skip to content

Instantly share code, notes, and snippets.

@dbonates
Last active May 23, 2017 15:49
Show Gist options
  • Select an option

  • Save dbonates/01819b30a956e756ff89765f72b56d57 to your computer and use it in GitHub Desktop.

Select an option

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
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