Subscripts 程式範例 — Apple’s The Swift Programming Language

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 Usage

var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]numberOfLegs["bird"] = 2

Subscript Options

subscript 可以有多個參數

例子: 矩陣

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.5matrix[1, 0] = 3.2

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade