欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift4 基础部分: Subscripts

程序员文章站 2024-02-20 14:47:10
...

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

Classes, structures, and enumerations can define 
subscripts, which are shortcuts for accessing the member 
elements of a collection, list, or sequence. You use 
subscripts to set and retrieve values by index without 
needing separate methods for setting and retrieval.
  • 类,结构体和枚举中可以定义下标,可以认为是访问对象、集合或序列的快捷方式,不需要再调用实例的单独的赋值和访问方法。

下标语法(Subscript Syntax)

我们直接来看一下例子:

struct TimeaTable{
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable = TimeaTable(multiplier: 3);
print("six times three is \(threeTimesTable[6])");

执行结果:

six times three is 18

下标选项(Subscript Options)

Subscripts can take any number of input parameters, and 
these input parameters can be of any type. Subscripts can 
also return any type. Subscripts can use variadic 
parameters, but they can’t use in-out parameters or 
provide default parameter values. 
  • 下标允许任意数量的入参,每个入参类型也没有限制。下标的返回值也可以是任何类型。下标可以使用变量参数可以是可变参数,但不能使用写入读出(in-out)参数或给参数设置默认值。

例子:

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, count: columns*rows);
    }
    func indexIsValidForRow(_ row: Int, _ column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns;
    }
    subscript(_ row: Int, _ column: Int) -> Double {
        get {
            assert(indexIsValidForRow(row,column), "Index out of range");
            return grid[(row * columns) + column];
        }
        set {
            assert(indexIsValidForRow(row,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;
print("matrix \(matrix.grid)");

执行结果:

matrix [0.0, 1.5, 3.2, 0.0]