標
擴充套件可以向現有型別新增新下標。
此示例使用給定索引獲取 String 內的字元:
Version = 2.2
extension String {
subscript(index: Int) -> Character {
let newIndex = startIndex.advancedBy(index)
return self[newIndex]
}
}
var myString = "StackOverFlow"
print(myString[2]) // a
print(myString[3]) // c
Version = 3.0
extension String {
subscript(offset: Int) -> Character {
let newIndex = self.index(self.startIndex, offsetBy: offset)
return self[newIndex]
}
}
var myString = "StackOverFlow"
print(myString[2]) // a
print(myString[3]) // c