Skip to content

Instantly share code, notes, and snippets.

@rmangino
Created January 30, 2017 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmangino/ce8679122c08d390e003c64d10ea0a28 to your computer and use it in GitHub Desktop.
Save rmangino/ce8679122c08d390e003c64d10ea0a28 to your computer and use it in GitHub Desktop.
import Foundation
// This example comes from https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
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)
let x = matrix[0][0] // error: "Cannot convert value of type 'Int' to expected arguemnt type `(Int, Int).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment