Created
January 30, 2017 17:24
-
-
Save rmangino/ce8679122c08d390e003c64d10ea0a28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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