K.Wu
K.Wu

Reputation: 3633

How to pass a "Sequence" of type "T" as a parameter in Swift?

Suppose I have a function that takes a sequence of "Person" objects. The sequence could be a simple array, or RealmSwift's Result, or List:

// A simple array
func someFunction(people: [Person]) {

}

// Result
func someFunction(people: Result<Person>) {

}

// List
func someFunction(people: List<Person>) {

}

Instead of having these 3 functions, I want to have only 1 function that takes a generic sequence of "Person" objects, something that looks like this:

func someFunction(people: Sequence<Person>) {

}

This way, I could pass an array, a Result or a List to the function and not have to worry that the types don't match. But obviously this is not allowed in Swift. How do I do that then?

Upvotes: 1

Views: 748

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17050

EDIT: Xcode 14.1 and Swift 5.7.1 were released today, and with these versions, you can now do this just with:

func someFunction(people: some Sequence<Person>) { ... }

Original answer is below.

--

You can do this with a where clause. Read about where clauses here:

https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID192

To answer your specific question, you can create a generic Sequence constraint and constrain its Element like so:

func someFunction<S: Sequence>(people: S) where S.Element == Person { ... }

Upvotes: 6

Related Questions