如何为String和NSAttributedString使用通用类型?

问题描述

我有一个扩展名,将bold设置为String

extension NSAttributedString {
    convenience init(format: NSAttributedString,makeBold: [String],regularText: [String]) {
        let mutableString = NSMutableAttributedString(attributedString: format)
        
        makeBold.forEach { string in
            let range = NSString(string: mutableString.string).range(of: "%bold%")
            let attributedString = NSAttributedString(string: string,attributes: [.font: UIFont.openSans(style: .bold,size: 15)])
            mutableString.replaceCharacters(in: range,with: attributedString)
            
        }
        
        regularText.forEach { text in
            let textRange = NSString(string: mutableString.string).range(of: "%regular%")
            mutableString.replaceCharacters(in: textRange,with: text)
        }
        self.init(attributedString: mutableString)
    }
}

它工作正常,但是我需要regularText: [String]才能接受[NSAttributedString]。我试图这样做:

convenience init<T>(format: NSAttributedString,regularText: [T])

但这给我一个错误:

mutableString.replaceCharacters(in: textRange,with: text)

带有错误文字

对实例方法“ replaceCharacters(in:with :)”的调用中不存在完全匹配项

generics不太熟悉,我不确定如何使它工作。任何帮助都会得到应用。

我在这里No exact matches in call to instance method error message in Swift

使用错误的类型是一个普遍的错误,所以我想我没有正确使用generics

编辑 如果我将regularText的类型从String更改为NSAttributedString,那么它可以正常工作而没有任何错误,那么为什么两者都不通用?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)