在 Swift 中,如何将“°”转换为“°”(即度数符号)?使用内置 Cocoa 实用程序(使用 NSAttributedString)

In Swift how do you convert "°" to "°" ( i.e degree symbol)? using built in Cocoa utility (with NSAttributedString)

当我从 http://www.weather-forecast.com/ 读取数据时,使用以下代码:

let urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)

urlContent 数据显示为 "°"。如何将其转换为“°”(即度数符号)?

编辑:使用公认的可伸缩性答案。但是如果你有一个奇怪的情况,你只想替换一种字符,这个答案就可以了。

度数符号在Swift中由字符串\u{00B0}表示。您可以将此事实与 stringByReplacingOccurencesOfString() 一起使用来执行以下操作:

let formattedUrlContent = urlContent.stringByReplacingOccurrencesOfString("°", withString: "\u{00B0}")

这在 Swift 2.0 中也有效!

stringByReplacingOccurrencesOfString("°", withString: "°")

像这样手动替换 HTML 转义字符确实不是一个好习惯。 Cocoa 已内置实用程序,可通过 NSAttributedString:

为您完成此操作
let input = "75°, partly cloudy"

let options: [String : AnyObject] = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : NSUTF8StringEncoding]

if let data = input.dataUsingEncoding(NSUTF8StringEncoding) {

    do {
        let unescaped = try NSAttributedString(data: data, options: options, documentAttributes: nil)
        print(unescaped.string) // "75°, partly cloudy"
    } catch {
        print(error)
    }
}