0

I am using a template project to try to build a new app. When I run the template project, I get an error saying: '[T] does not have a member named 'indexOf'.

The existing code in the Array+RemoveObject.swift doc is:

import Foundation
public func removeObject<T: Equatable>(object: T, inout fromArray array: [T])
{ let index = array.indexOf(object)
    if let index = index {
        array.removeAtIndex(index)
    }
}

Is the problem the use of indexOf? The odd thing is that when I tried using the solution of someone who answered a similar question, I got around 100 errors from the bond framework.

1 Answers1

1

You function on its own works fine for me (Swift 2.1.1, Xcode 7.2). It seems as if you want this function to be a method of a public class of yours. For a minimum working example, you need at least to wrap your removeObject() method within the class you want it to belong to. Note also that you needn't use a separate line for assigning the result from .indexOf(..) call (possibly nil), but can add assignment and nil check in a single if let statement.

public class MyArrayOperations {

    // ...

    static public func removeObject<T: Equatable>(object: T, inout fromArray array: [T])    {
        if let index = array.indexOf(object) {
            array.removeAtIndex(index)
        }
    }

}

var arr = ["1", "2","3"]
MyArrayOperations.removeObject("2", fromArray: &arr)
print(arr) // ["1", "3"]

Also note that you can explicitly state the same behaviour using two generics, in case you want the array itself to conform to some protocol. You then use one separate generic for the array type and one for its elements, thereafter specifying that the element type should conform to the Generator.Element type of the array. E.g.:

func removeObject<T: Equatable, U: _ArrayType where U.Generator.Element == T>(object: T, inout fromArray array: U) {
    if let index = array.indexOf(object) {
        array.removeAtIndex(index)
    }
}

With this approach, you could add an additional protocol at type constraint for the array generic U in the function signature above, e.g.

func removeObject<T: Equatable, U: protocol<_ArrayType, MyProtocol> where U.Generator.Element == T>(object: T, inout fromArray array: [T]) { ...

This can be especially useful when "simulating" generic Array extensions that conforms to some protocol. See e.g. the following for such an example:

Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192