在Swift中,類、結構體和枚舉都是支持下標語法的。
什么是下標語法?使用過數組、字典的朋友都見過array[index]。通過這樣的方式可以設置數據和取數,會很方便也很簡潔。你可以給一個類定義多個下標,也可以在一個下標中定義一個或多個參數。
下標的關鍵字是subscript,常用格式如下:
~~~
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
~~~
下面我們以數組為例,給大家介紹下標的創建和使用。
~~~
/// array結構體
struct TestArray {
/// 內部數組
var array = Array<Int>()
// MARK: 下標使用
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[3])") // 4
print("\(array[4])") // 程序停止
~~~
### 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-10-30 | 根據 [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Subscripts總結 |
版權所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結構體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運算符(Advanced Operators)