點擊查看源碼git
func testSubscripts() { //下標關鍵字subscript //array測試 struct TestArray { //內部數組 var array = Array<Int>() //下標使用 subscript(index: Int) -> Int { get { assert(index < array.count, "下標越界") return array[index] } set { while array.count <= index { array.append(0) } array[index] = newValue } } } var array = TestArray() array[3] = 4; //經過下標設置值 print(array) print("\(array[3])") //4 print("\(array[4])") //程序中止 }