Subscripts

作者: 宋奕Ekis | 来源:发表于2021-08-10 10:23 被阅读0次

Subscripts can be defined in Classes, Stuctures and Enmuerations.

We can look at it as if a special method.

Subscript Syntax

subscript(index: Int) -> Int {
    get {
        // Return an appropriate subscript value here.
    }
    set(newValue) {
        // Perform a suitable setting action here.
    }
}
struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"

Subscript Options

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }
    func indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2

We can see the example above, we make a Matrix based on an array, and two subscripts, and we implement a subscriptincluding two parameters to access the Matrix.

Type Subscripts

Like type method, we can use static (class instead in Class to support override in subclass) to prefix the subscriptmethod as a type subscript.

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
    static subscript(n: Int) -> Planet {
        return Planet(rawValue: n)!
    }
}
let mars = Planet[4]
print(mars)

Let’s think!

相关文章

  • Subscripts

    附属脚本可用于类、结构体和枚举。通过在[]内传入一个或多个参数,得到返回值。例如someArray[index]、...

  • Subscripts

    Subscripts can be defined in Classes, Stuctures and Enmue...

  • Swift - Subscripts

    输入参数能够为任意类型,Subscripts 能够返回任意类型 能够使用多变参数,但是不能使用输入输出参数和默认参...

  • Subscripts(下标)

    //离上次学习swift过了好久,这才刚开始学习swift呀,坚持。 //下标//“下标可以定义在类、结构体和枚举...

  • subscripts(下标)

    subscripts(下标): 访问对象中数据的快捷方式所谓下标脚本语法就是能够通过, 实例[索引值]来访问实例中...

  • Subscripts (下标)

    Classes, structures, and enumerations can definesubscript...

  • iOS项目从 Swift3.2 升级到 Swift4.0 报错解

    Swift3.2 --> Swift4.0 报错 Subscripts returning String wer...

  • 05 来,自定义一个swift的subscript

    本文参考原文为Implementing Custom Subscripts in Swift,欢迎阅读原文。 下标...

  • 下标脚本(Subscripts)

    用下标脚本访问一个数组(Array)实例中的元素可以这样写 someArray[index] ,访问字典(Dict...

  • OneDayOneSwift[12] - Subscripts

    下标脚本 可以定义在类(Class)、结构体(structure)和枚举(enumeration)中,是访问集合(...

网友评论

    本文标题:Subscripts

    本文链接:https://www.haomeiwen.com/subject/risxbltx.html