Search code examples
swiftsubscript

What are lists in Swift, and how can I use subscripts with a list?


The Swift Programming Guide (Swift 5.1 Edition) says that subscripts can be used to access members of “a collection, list, or sequence.” Collection and Sequence are defined protocols in Swift and are well documented. Do lists exist in Swift as a separate entity? If so, what is the syntax for a list subscript?


Solution

  • It would be better if The Swift Programming Language (the book) didn't say “ a collection, list, or sequence”. As you point out, Swift has standard Collection and Sequence types. It does not have any standard type named List.

    The closest thing would be Array:

    let words: Array<String> = ["Mark", "Cowan"]
    // or words: [String]
    let firstWord = words[0]