If you just need to convert only numeric entities, you can use CFStringTransform(_:_:_:_:)
.
Declaration
func CFStringTransform(_ string: CFMutableString!,
_ range: UnsafeMutablePointer<CFRange>!,
_ transform: CFString!,
_ reverse: Bool) -> Bool
...
transform
A CFString object that identifies the transformation to apply. For a
list of valid values, see Transform Identifiers for CFStringTransform.
In macOS 10.4 and later, you can also use any valid ICU transform ID
defined in the ICU User Guide for Transforms.
(Code tested in Swift 3/Xcode 8, iOS 8.4 simulator.)
func decodeNumericEntities(_ input: String) -> String {
let nsMutableString = NSMutableString(string: input)
CFStringTransform(nsMutableString, nil, "Any-Hex/XML10" as CFString, true)
return nsMutableString as String
}
print(decodeNumericEntities("from 北京")) //->from 北京
Or if you prefer computed property and extension:
extension String {
var decodingNumericEntities: String {
let nsMutableString = NSMutableString(string: self)
CFStringTransform(nsMutableString, nil, "Any-Hex/XML10" as CFString, true)
return nsMutableString as String
}
}
print("from 北京".decodingNumericEntities) //->from 北京
Remember these codes above do not work for named character entities, such as >
or &
.
(From this thread in スタック・オーバーフロー(Japanese StackOverflow).)