Swift重写初始化(格式:String,uu)参数:CVarArg…)

Swift重写初始化(格式:String,uu)参数:CVarArg…),swift,switch-statement,protocols,control-flow,Swift,Switch Statement,Protocols,Control Flow,我试图重写在String格式中找到的标准String Frand方法,该方法使用字符串,并用字符串和整个范围类型替换包含%i的所有值,其中包含int和%@。p> 因为我不知道c,所以我把初始值设定项从 init(format: String, _ arguments: CVarArg) { 到 现在,我在字符串扩展中使用它为int工作 init(format: String, _ arguments: [Any]) { var copy = format

我试图重写在String格式中找到的标准String Frand方法,该方法使用字符串,并用字符串和整个范围类型替换包含%i的所有值,其中包含int和%@。p> 因为我不知道c,所以我把初始值设定项从

init(format: String, _ arguments: CVarArg) {

现在,我在字符串扩展中使用它为int工作

  init(format: String, _ arguments: [Any]) {
            var copy = format
            for argument in arguments {
                switch argument {
                case let replacementInt as Int:
                    String.handleInt(copy: &copy, replacement: String(replacementInt))
                default:
                    self = format
                }
            }
        self = copy
    }

private static func handleInt(copy: inout String, replacement: String) {
但是,由于我希望它适用于所有值,所以我尝试使用开关查找任何类型,该类型具有使用Stringvalue初始值设定项转换为字符串所需的LossStringConvertible协议

     init(format: String, _ arguments: [Any]) {
        var copy = format
        for argument in arguments {
            switch argument {
            case let replacementInt as LosslessStringConvertible:
                String.handleAnyValue(copy: &copy, replacement: String(replacementInt))
            default:
                self = format
            }
        }
    self = copy
}
但是,在应用StringreplacementInt时,我遇到以下错误

协议类型“LosslessStringConvertible”无法符合 “LosslessStringConvertible”,因为只有具体类型才能符合 协议

奖金
如果我能做到这一点,而不用导入任何库,也不用简单地使用swift进行编写,那将是一个额外的好处。

您可以将符合LosslessStringConvertible作为参数的要求:

init<S: LosslessStringConvertible>(format: String, _ arguments: [S])
此解决方案的限制是,例如,不符合LosslessStringConvertible的实例类型将导致错误。例如:

class Z {}
let z = Z()
var y: String = String(format: "%i %@ %@", 5, "five", z) // Compilation error: Argument type 'Z' does not conform to expected type 'CVarArg'

错误很明显。字符串初始值设定项的参数必须是一个具体类型,而不是协议。我如何才能为任何可以是Int或String的类型创建一个具体类型,或者根本不可能,我必须将类型转换为Int。@vadian为什么不使用第二种情况?case let replacementin作为Int,case let replacementString作为String。handleAnyValue中的参数替换可以声明为LosslessStringConvertible或generic T
var x: String  = String(format: "%i %@", 5, "five")
print(x) // prints "5 five"
class Z {}
let z = Z()
var y: String = String(format: "%i %@ %@", 5, "five", z) // Compilation error: Argument type 'Z' does not conform to expected type 'CVarArg'