1

Swift's filter method is defined as follows:

func filter(includeElement: (T) -> Bool) -> [T]

Why does filter definition in Swift's array does not have <T> in its definition (i.e. filter(...))?

1

2 Answers 2

2

filter is a method of the Array<T> class, so T is specified at class level and there is no need to replicate that in the method - actually doing that at method level is a mistake:

struct Array<T> ... {
    func filter<V>(includeElement: (V) -> Bool) -> [V]
}

because V is a different type that has no relationship with T (unless you set constraints in the generic definition). By mistake I mean T and V are different types, whereas it could be thought they are the same. Having a generic class with a generic method is perfectly legit though.

Sign up to request clarification or add additional context in comments.

Comments

0

it is because this function is defined in an extension to Array struct and the definition of Array has the in its definition : struct Array

class AA<T> {
}

extension AA {
    func something(aThing: T) -> T{
        return aThing
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.