Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What type do I use for a Sequence of Strings

I want to write a function that accepts an argument that is a Sequence of Strings (not necessarily an array of Strings, but anything that implements the Sequence protocol where the items in the sequence are Strings).

Actually, I’d like to pass in the keys to a dictionary that is keyed by strings (preferably, without creating a temporary array).

I can’t seem to find the right syntax to specify that type for the argument.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

func doSomething<S: Sequence>(with seq: S) where S.Element == String

Or as per suggestion in comments by @LeoDabus you could include also substrings and other types conforming to StringProtocol by constraining the sequence’s element:

func doSomething<S: Sequence>(with seq: S) where S.Element: StringProtocol
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading