Stackoverflow上的found this extension。但是,出现了错误。如何解决此错误?
Cannot invoke initializer for type 'NSAttributedString' with an argument list of type '(data: NSData, options: [String : AnyObject], documentAttributes: NilLiteralConvertible, error: NilLiteralConvertible)'
错误在" let referencedString"。
extension String {
init(htmlEncodedString: String) {
let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)! //ERROR HERE!
self.init(attributedString.string)
}
}
答案 0 :(得分:8)
查看the docs我相信你有正确的方法,但请注意Swift 2有错误处理,所以你需要这样做:
extension String {
init(htmlEncodedString: String) {
do {
let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
self.init(attributedString.string)
} catch {
fatalError("Unhandled error: \(error)")
}
}
}
我在游乐场测试了它,它很乐意编译。