subscript(参数1,参数2...)->返回值{ get{ } set(newValue){ } }
struct CSDN{ var ID:Int = 123456 var name:String = "hello_hwc" subscript(index:Int)->Any?{ switch(index){ case 0:return ID case 1:return String default:return nil //default:assert("Index out of range") } } } var instance = CSDN() if let temp = instance[2]{ println("success") }
我们来做一个复杂的例子,通过扩展String来通过下标的方式获得子字符串,同时提供几个substring的方法
extension String { subscript (r: Range<Int>) -> String { get { let subStart = advance(self.startIndex, r.startIndex, self.endIndex) let subEnd = advance(subStart, r.endIndex - r.startIndex, self.endIndex) return self.substringWithRange(Range(start: subStart, end: subEnd)) } } func substring(from: Int) -> String { let end = countElements(self) return self[from..<end] } func substring(from: Int, length: Int) -> String { let end = from + length return self[from..<end] } func substring(from:Int, to:Int) ->String { return self[from..<to] } } var str = "hello world" var str1 = str.substring(6) var str2 = str.substring(0,to:5) var str3 = str.substring(0,length:5)