我有将html符号转换为字符串的扩展名:
extension String {
func convertHtmlSymbols() throws -> String? {
guard let data = data(using: .utf8) else { return nil }
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil).string
}
}
此扩展程序运行良好。但是我需要将此扩展转换为类"转换器":
class Converter{
func convertHtmlSymbols(data: String) throws -> String? {
guard let data = data(using: .utf8) else { return nil }
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil).string
}
}
但是我收到了这个错误:
错误:无法调用非函数类型的值
答案 0 :(得分:5)
在String
扩展方法中,
guard let data = data(using: .utf8)
是
的快捷方式guard let data = self.data(using: .utf8)
即。在data(using:)
上调用self
方法。在你的班上
你想在给定的字符串参数上调用它(也会发生这种情况
被称为“数据”),因此它必须是
guard let data = data.data(using: .utf8)
重命名参数可以减少混乱!
答案 1 :(得分:3)
正如Martin R建议:
class Converter{
func convertHtmlSymbols(input: String) throws -> String? {
guard let data = input.data(using: .utf8) else { return nil }
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil).string
}
}
原因是
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
是一个在Converter
类中它不是成员/财产,所以它看不到它,也不能使用它。
请参阅Apple Doc
答案 2 :(得分:0)
我会这样做:
class Converter{
static func convertHtmlSymbols(_ string: String) throws -> String? {
guard let data = string.data(using: .utf8) else { return nil }
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil).string
}
}
而不是这样称呼:
try Converter.convertHtmlSymbols("your string here")
答案 3 :(得分:0)
试试这个:
class Converter{
func convertHtmlSymbols(data: String) throws -> String? {
return try? NSAttributedString(data: data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil).string
}
}