在Swift中,類、結(jié)構(gòu)體和枚舉都是支持下標(biāo)語法的。
什么是下標(biāo)語法?使用過數(shù)組、字典的朋友都見過array[index]。通過這樣的方式可以設(shè)置數(shù)據(jù)和取數(shù),會很方便也很簡潔。你可以給一個類定義多個下標(biāo),也可以在一個下標(biāo)中定義一個或多個參數(shù)。
下標(biāo)的關(guān)鍵字是subscript,常用格式如下:
~~~
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
~~~
下面我們以數(shù)組為例,給大家介紹下標(biāo)的創(chuàng)建和使用。
~~~
/// array結(jié)構(gòu)體
struct TestArray {
/// 內(nèi)部數(shù)組
var array = Array<Int>()
// MARK: 下標(biāo)使用
subscript(index: Int) -> Int {
get {
assert(index < array.count, "下標(biāo)越界")
return array[index]
}
set {
while array.count <= index {
array.append(0)
}
array[index] = newValue
}
}
}
var array = TestArray()
array[3] = 4; // 通過下標(biāo)設(shè)置值
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 | 根據(jù) [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Subscripts總結(jié) |
版權(quán)所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數(shù)
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結(jié)構(gòu)體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(biāo)(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協(xié)議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運(yùn)算符(Advanced Operators)
