I am trying to change colour for all numbers present in a string in swift
code.Example:
var mystring = \"abc 3423 opqrs 474598 lmno 343543\"
Here's an extension using Swift 5 using Zig's answer as reference:
extension String {
func changeColorForNumbers() -> NSMutableAttributedString {
let red = [NSAttributedString.Key.foregroundColor: UIColor.red]
let myAttributedString = NSMutableAttributedString()
for letter in self.unicodeScalars {
let myLetter : NSAttributedString
if CharacterSet.decimalDigits.contains(letter) {
myLetter = NSAttributedString(string: "\(letter)", attributes: orange)
} else {
myLetter = NSAttributedString(string: "\(letter)")
}
myAttributedString.append(myLetter)
}
return myAttributedString
}
}