//: Playground - noun: a place where people can play import Foundation /* 下标: 1.所有的swift类型(枚举, 类和结构体)都支持定义下标 2.同一个类型可以定义多个下标 3.通过下标的形参列表或者返回值类型来区分不同的下标 4.同一类型中定义多个不同的下标被称为下标重载 */ class Person { var x:Int? var y:Int? var width:Int? var height:Int? // 通过下标进行访问时会调用 // 形参列表, 与参数的形参列表的用法基本相同, 但是不支持指定外部参数和默认值 // 下标的返回值类型可以是任何有效的类型 subscript (index: Int) -> Int { get{ switch index { case 0: return self.x! case 1: return self.y! case 2: return self.width! case 3: return self.height! default: return 0 } } // 通过下标进行设置时会调用 set(newValue){ switch index { case 0: self.x = newValue case 1: self.y = newValue case 2: self.width = newValue case 3: self.height = newValue default: break } } } } var p = Person() p.x = 1 p.y = 2 p.width = 3 p.height = 4 // 通过下标访问属性 p[0] // 通过下标修改属性 p[1] = 11111 p.y
原文:http://www.cnblogs.com/Rinpe/p/5182151.html