[Swift] Type component ~ Subscript ~

What is a subscript

A subscript is a collection of arrays, dictionaries, etc. A grammar for unified access to elements.

You used it in the following situations!


let array = [1, 2, 3]
let firstElement = array[0]   // 1

let dictionary = ["a": 1, "b": 2, "c": 3]
let elementA = dictionary["a"]   // 1

Definition method

To define a subscript Specify the argument and return type after the ** subscript keyword **, and define the setter or getter in {}.

The method of defining the types of arguments and return values ​​is the same as for functions, In subscripts, all external argument names default to _.

Also, getters and setters Similar to that of Computed Properties.

The shape is as follows.


subscript(argument) ->Return type{
   get {
Processing that returns a value with a return statement
   }
   
   set {
Process to update the value
   }
}

To use subscripts Add the argument enclosed in [] to the variable or constant to which the instance of the type is assigned, Write as variable name [argument].

Getter is called when getting the value, The setter is called when updating the value.

I wrote a sample code.

A getter is used because print (arrayInt [1]) gets the value. 1 is entered in the argument index of subscript, and the value of array [1] is returned.

Since arrayInt [1] = 4 is a value update, a setter is used. Since the newValue of array [index] = newValue is a new value, 4 is applicable.


struct ArrayInt {
    var array: [Int]
    
    subscript(index: Int) -> Int {
        get {
            return array[index]
        }
        
        set {
            array[index] = newValue
        }
    }
}

var arrayInt = ArrayInt(array: [1, 2, 3])
print(arrayInt[1])

arrayInt[1] = 4
print(arrayInt[1])

Execution result
2
4

The same flow applies when there are multiple arguments. I just changed it to a two-dimensional array, so I didn't do any special difficult processing.


struct ArrayInt {
    var array: [[Int]]
    
    subscript(row: Int, column: Int) -> Int {
        get {
            return array[row][column]
        }
        
        set {
            array[row][column] = newValue
        }
    }
}

var arrayInt = ArrayInt(array: [
                            [1, 2, 3],
                            [4, 5, 6],
                            [7, 8, 9]
])
print(arrayInt[1,1])

Execution result
5

Omission of setter

Similar to Computed Properties ** The getter definition is also required in the subscript. ** **

However, the definition of setter is arbitrary. If the setter does not exist, the get keyword and {} can be omitted.

The code when the setter is omitted is as follows.


struct ArrayInt {
    var array: [Int]
    
    subscript(index: Int) -> Int {
        return array[index]
    }
}

var arrayInt = ArrayInt(array: [1, 2, 3])
arrayInt[1]   // 2

Even though the setter is omitted Attempting to update the value will result in a compile error.


struct ArrayInt {
    var array: [Int]
    
    subscript(index: Int) -> Int {
        return array[index]
    }
}

var arrayInt = ArrayInt(array: [1, 2, 3])
arrayInt[1]   // 2
arrayInt[1] = 4   //Compile error

Error details: Cannot assign through subscript: subscript is get-only Japanese translation: Cannot be assigned by subscript: subscript is for acquisition only (Since subscript was abbreviated as subscript, I changed it back to subscript.)

Overload

Subscripts can be overloaded as well as methods.

If you prepare multiple subscripts with the same name that take arguments and return values ​​of different types You can switch the subscript according to the processing at that time.

** For example, the Array \ type also has a subscript overloaded. ** **

A subscript that takes an Int type as an argument and returns an Element type element, Take the Range \ type as an argument and take the ArraySlice \ type, A subscript that returns a slice is provided.

** Slices represent part of a collection. ** **


let array = [1, 2, 3, 4]
let element = array[0]   // Element
let slice = array[0...2]   // ArraySlice<Element>

The above is the explanation of the subscript.

I think it will be necessary knowledge when defining the type of the array I don't think it will hurt to remember.

Since there is an image that arrays are involved when dealing with data etc. I will understand it well and make it available at all times!

There are other articles that describe the components of the type, so be sure to check them out as well!

-[Swift] Type component-Type basics- -[Swift] type component-property first part- ・ [Swift] type component ~ initializer ~ -[Swift] type component ~ method ~[Swift] type component ~ extension ~ -[Swift] Type component ~ Type nesting ~

Thank you for watching until the end.

Recommended Posts

[Swift] Type component ~ Subscript ~
[Swift] Type component ~ Initializer ~
[Swift] Type component ~ Method ~
[Swift] Type component ~ Property Part 2 ~
[Swift] Type type ~ Enumeration type ~
[Swift] Type type ~ Structure ~
[Swift] Type components ~ Type nesting ~
[Swift] Type design guidelines
[Swift] Shared enumeration type
[Swift] Type type-Class sequel-
[Swift] Summary about Bool type
[Swift] Type type-Class first part-
Great Swift pointer type commentary
[Swift] Converts a UInt64 type integer to [UInt8]