代码之家  ›  专栏  ›  技术社区  ›  J. Doe

在数组扩展中采用相同数组的方法签名

  •  1
  • J. Doe  · 技术社区  · 7 年前

    我想在数组扩展中编写一个泛型方法,它采用的参数类型也是元素类型相同的数组(对于数组扩展和参数的调用方)。这就是我的意思(但没有一个有效):

    extension Array {
        func doSomethingWithAnotherArray(arr: Self) {
    
        }
    }
    
    extension Array {
        func doSomethingWithAnotherArray<T: Array<Element>>(arr: T){
    
        }
    }
    
    extension Array {
        func doSomethingWithAnotherArray<T: Array<U>, U>(arr: T) where U == Element{
    
        }
    }
    

    因此,我可以将其用作:

    let x = [1, 2]
    let y = [3, 4]
    x.doSomethingWithAnotherArray(arr: y)
    Since x and y has the same elements.
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Robert Dresler Gustavo Vollbrecht    7 年前

    Array

    extension Array {
        func doSomethingWithAnotherArray(arr: Array) {
            ... // do something  
        }
    }
    

    [Int].doSomethingWithAnotherArray(arr: [Int]) // works
    [Int].doSomethingWithAnotherArray(arr: [String]) // doesn't work
    
        2
  •  1
  •   Arkku    7 年前

    如果唯一的限制是 Element 参数的值与接收方的值相同:

    extension Array {
        func doSomethingWithAnotherArray(arr: Array<Element>) {
            // …
        }
    }
    

    编辑:如中所示 this answer Array 足够了,因为这个函数本身不是泛型的,并且在泛型类型的上下文中, 排列 已专用于接收器的类型。

    元素 ,使用 extension Array where Element … .