Introduction

You can add subscripting to your own classes.

You define what it means to get and set values via a subscript using the subscript keyword.

For example, the following code access the individual bits inside an 8-bit integer. You can do this with subscripting, like so:

Demo

// Extend the unsigned 8-bit integer type 
extension UInt8 { /*from  ww w. j av a2 s. co  m*/
    // Allow subscripting this type using UInt8s 
    subscript(bit: UInt8) -> UInt8 { 
        // This is run when you do things like "value[x]" 
        get { 
            return (self >> bit & 0x07) & UInt8(1) 
        } 

        // This is run when you do things like "value[x] = y" 
        set { 
            let cleanBit = bit & 0x07 
            let mask  : UInt8 = 0xFF ^ (1 << cleanBit) 
            let shiftedBit = (newValue & 1) << cleanBit 
            self = self & mask  | shiftedBit 
        } 
    } 
} 
var byte  : UInt8 = 212 

print(byte[0])
print(byte[2])
print(byte[5])
print(byte[6])

// Change the last bit 
byte[7] = 0 
// The number is now changed! 
print(byte)

Result

Related Topic