通常,要针对 [String]
编写扩展,您可以这样做...
extension Array where Element == String {
....
}
但是,有时我没有 [String]
,而是 [Substring]
。如何编写支持其中任何一个的扩展?
最佳答案
String
和Substring
都符合StringProtocol
协议(protocol),
所以你可以定义
extension Array where Element: StringProtocol {
// ...
}
标准库中的许多函数已被泛化
接受 StringProtocol
参数,例如 Int
初始化器
convenience init?<S>(_ text: S, radix: Int = default) where S : StringProtocol
这样您就可以使用String
和Substring
来调用它:
let n = Int("1234")
let m = Int("1234".dropFirst())
关于swift - 如何编写一个扩展来支持 [String] 和 [Substring]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206181/