Subscripts

Introduction

Welcome to lesson 7, Subscripts, of The Swift Fundamentals with Bob. What if I told you that you may create a shortcut?

Problem

I’d love to have a shortcut instead of calling a method.

Normal Method

Create a class called, HelloKitty which contains a method that returns a string value.

  1. struct HelloKitty {
  2. func saySomething() -> String {
  3. return "I'm Cute"
  4. }
  5. }

Create an instance and call saySomething()

  1. let babe = HelloKitty()
  2. babe.saySomething() // "I'm Cute"

Introducing Subscripts

Subscripts are analogous to methods. Yet, there is no name. Instead you add the keyword, subscript.

  1. struct WeekDays {
  2. var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
  3. subscript(index: Int) -> String {
  4. return days[index]
  5. }
  6. }

Call the subscript by adding [] at the end of the instance.

  1. let myDays = WeekDays()
  2. myDays[0] // "Monday"
  3. myDays[1] // "Tuesday"

Dictionary

When you access elements in a dictionary, it always returns an optional type.

  1. var info = ["Height": 183, "Body Fat": 12.5, "Weight": 76]
  2. let height = info["Height"] // height is an optional string

Artificial Dictionary

Let us access an element without returning an optional type using subscripts.

  1. struct HealthInfo {
  2. var info = ["Height": 183, "Body Fat": 12.5, "Weight": 76]
  3. subscript(key: String) -> Double {
  4. if let newInfo = info[key] {
  5. return newInfo
  6. } else {
  7. return 0
  8. }
  9. }
  10. }

Important: You may use guard instead.

Access Elements

Return non-optionals using the subscript method.

  1. let bob = HealthInfo()
  2. bob["Height"] // 183
  3. bob["Body Fat"] // 12.5
  4. bob["123456789"] // 0

Shortcoming of Subscript

No context means = ☠️

Practical Usage

  1. Get the number of rows in table/collection
  2. Anything has to do with pairs and collection types

Source Code

1107_subscripts.playground

Conclusion

Now you understand the meaning of creating a shortcut. However, subscripts often leads to confusion due to no explicit name. Swift engineers recommend that brevity is not the ultimate goal. Effective communication trumps everything else.

In the next lesson, you will learn the fundamental difference between structs and classes. In other words, you will learn the meaning of reference types and value types.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.