类,结构和枚举可以定义下标,这些下标是访问集合,列表或序列的成员元素的快捷方式。
例
struct DaysOfWeek { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] subscript(index: Int) -> String { get { return days[index] } set { days[index] = newValue } } }
下标用法
var week = DaysOfWeek() //您可以通过array [index]在索引处访问数组的元素。 debugPrint(week[1]) debugPrint(week[0]) week[0] = "Sunday" debugPrint(week[0])
下标可以采用任意数量的输入参数,并且这些输入参数可以是任何类型。下标也可以返回任何类型。下标可以使用可变参数和可变参数,但不能使用输入输出参数或提供默认参数值。
示例
struct Food { enum MealTime { case Breakfast, Lunch, Dinner } var meals: [MealTime: String] = [:] subscript (type: MealTime) -> String? { get { return meals[type] } set { meals[type] = newValue } } }
用法
var diet = Food() diet[.Breakfast] = "Scrambled Eggs" diet[.Lunch] = "Rice" debugPrint("I had \(diet[.Breakfast]) for breakfast")