是否可以在 Swift 中实现类似的功能?
extension Array {
func processItems<Element: Protocol1>() {
for item in self {
// deal with Protocol1 objects
}
}
func processItems<Element: Protocol2>() {
for item in self {
// deal with Protocol2 objects
}
}
}
我想要实现的是扩展 Array
并根据数组中元素的类型重载 processItems
。
另一种方法是要么拥有一个函数,要么使用可选的强制转换/绑定(bind),但是我会以这种方式失去类型安全,并且最终可能会得到一个包含很多 if if-let< 的庞大函数
的
func processItem() {
for item in self {
if let item = item as? Protocol1 {
// deal with Protocol1 objects
} else if let item = item as? Protocol2 {
// deal with Protocol2 objects
}
}
},
或将 processItems
声明为自由函数:
func processItems<T: Protocol1>(items: [T]) {
// ...
}
func processItems<T: Protocol2>(items: [T]) {
// ...
}
但是我想知道我是否可以将该函数“嵌入”到 Array
类中,以使其保持本地化。如果这是可能的,那么该技术可以应用于其他泛型类(内置或自定义)。
最佳答案
这个怎么样?
extension Array where Element: Protocol1 {
func processItems() {
for item in self { // item conforms to Protocol1
...
关于swift - 根据其元素的类型重载 Array 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671396/