Swift Array.insert generics

前端 未结 5 1672
盖世英雄少女心
盖世英雄少女心 2020-12-07 03:02
func getIndex(valueToFind: T) -> Int? {...}

mutating func replaceObjectWithObject(obj1: T, obj2: T) {
    if let index =          


        
5条回答
  •  旧巷少年郎
    2020-12-07 03:21

    This is actually not possible via an extension under the existing system of protocols and generics in Swift - you can't add additional constraints to the generic subtype of a type, so you can't extend Array with a method that requires that its contents conform to Equatable.

    You can see this restriction in action with the built-in Array type -- there's no myArray.find(element) method, but there is a global function find() that takes a collection and an element, with a generic constraint that the collection's elements are Equatable:

    func find(domain: C, value: C.Generator.Element) -> C.Index?
    

    You can do this for your method - you just need to write a similar top-level function:

    func replaceObjectWithObject(inout collection: C, obj1: C.Generator.Element, obj2: C.Generator.Element) {
        if let index = find(collection, obj1) {
            removeAtIndex(&collection, index)
            insert(&collection, obj2, atIndex: index)
        }
    }
    
    var myArray = [1, 2, 3, 4, 5]
    replaceObjectWithObject(&myArray, 2, 7)
    // 1, 2, 7, 4, 5
    

提交回复
热议问题