Swift中泛型函数如何支持多种CustomStringConvertible类型混用?
解决方案
你的问题出在原泛型函数的可变参数要求所有参数必须是同一泛型类型T。当传入"hello"(String)和100(Int)时,Swift会自动推断T为String,导致Int类型参数无法转换为String,从而报错。
要实现接受任意遵循CustomStringConvertible协议的类型(无需统一类型),可以直接将可变参数的类型指定为CustomStringConvertible,而不是泛型T:
func customPrint(_ values: CustomStringConvertible...) { let output = values.map { String(describing: $0) }.joined(separator: " ") print(output) }
说明
- 这里的可变参数
values: CustomStringConvertible...允许传入任意数量、任意类型(只要遵循CustomStringConvertible)的参数,编译器会在编译阶段自动检查参数是否符合协议要求,比用Any...更安全。 - 使用
map将每个元素转换为字符串,再通过joined(separator: " ")拼接,比原代码的forEach拼接更简洁高效。
测试调用:
customPrint("hello", 100, 3.14, true) // 输出:hello 100 3.14 true
内容的提问来源于stack exchange,提问作者swiftPunk
相关产品推荐
相关产品推荐

