本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。
系列文章:
- Swift4 基礎(chǔ)部分:The Basics
- Swift4 基礎(chǔ)部分:Basic Operators
- Swift4 基礎(chǔ)部分:Strings and Characters
- Swift4 基礎(chǔ)部分:Collection Types
- Swift4 基礎(chǔ)部分:Control Flow
- Swift4 基礎(chǔ)部分:Functions
- Swift4 基礎(chǔ)部分:Closures
- Swift4 基礎(chǔ)部分: Enumerations
- Swift4 基礎(chǔ)部分: Classes and Structures
- Swift4 基礎(chǔ)部分: Properties
- Swift4 基礎(chǔ)部分: Methods
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.
- 類,結(jié)構(gòu)體和枚舉中可以定義
下標(biāo),可以認(rèn)為是訪問對象、集合或序列的快捷方式,不需要再調(diào)用實例的單獨的賦值和訪問方法。
下標(biāo)語法(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])");
執(zhí)行結(jié)果:
six times three is 18
下標(biāo)選項(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.
- 下標(biāo)允許任意數(shù)量的入?yún)?,每個入?yún)㈩愋鸵矝]有限制。下標(biāo)的返回值也可以是任何類型。下標(biāo)可以使用變量參數(shù)可以是可變參數(shù),但不能使用寫入讀出(in-out)參數(shù)或給參數(shù)設(shè)置默認(rèn)值。
例子:
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)");
執(zhí)行結(jié)果:
matrix [0.0, 1.5, 3.2, 0.0]