我有将 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
}
}
这个扩展很好用。但我需要将此扩展转换为类“Converter”中的函数:
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
}
}
但是我得到了这个错误:
error: Cannot call value of non-function type
最佳答案
在String
扩展方法中,
guard let data = data(using: .utf8)
是
的捷径guard let data = self.data(using: .utf8)
即data(using:)
方法在 self
上被调用。在你的类(class)
你想在给定的字符串参数上调用它(这也会发生
被称为“数据”),因此它必须是
guard let data = data.data(using: .utf8)
重命名参数可以减少困惑!
关于ios - 将扩展转换为类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852438/