Reader small image

You're reading from  Swift Data Structure and Algorithms

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785884504
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Mario Eguiluz Alebicto
Mario Eguiluz Alebicto
author image
Mario Eguiluz Alebicto

Mario Eguiluz Alebicto is a software engineer with over 15 years of experience in development. He started developing software with Java, later switched to Objective-C when the first iPhone delighted the world, and now, he is working with Swift and involved in backend technologies. He loves to code, build exciting projects, and learn new languages and frameworks. Apart from software development, Mario loves to travel, learn new hobbies, practice sports, and considers himself a hardcore gamer, which he has been since he was a child.
Read more about Mario Eguiluz Alebicto

Right arrow

Implementing subscripting


Subscripts can be defined for classes, structures, and enumerations. They are used to provide a shortcut to elements in collections, lists, and sequence types by allowing terser syntax. They can be used to set and get elements by specifying an index instead of using separate methods to set or retrieve values.

Subscript syntax

You can define a subscript that accepts one or more input parameters, the parameters can be of different types, and their return value can be of any type. Use the subscript keyword to define a subscript, which can be defined as read-only, or provide a getter and setter to access elements:

class MovieList { 
    private var tracks = ["The Godfather", "The Dark Knight", "Pulp Fiction"] 
     
    subscript(index: Int) -> String { 
         
        get { 
            return self.tracks[index] 
        } 
         
        set { 
            self.tracks[index] = newValue 
        } 
...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Swift Data Structure and Algorithms
Published in: Nov 2016Publisher: PacktISBN-13: 9781785884504

Author (1)

author image
Mario Eguiluz Alebicto

Mario Eguiluz Alebicto is a software engineer with over 15 years of experience in development. He started developing software with Java, later switched to Objective-C when the first iPhone delighted the world, and now, he is working with Swift and involved in backend technologies. He loves to code, build exciting projects, and learn new languages and frameworks. Apart from software development, Mario loves to travel, learn new hobbies, practice sports, and considers himself a hardcore gamer, which he has been since he was a child.
Read more about Mario Eguiluz Alebicto