subscripts(下标)是访问对象数据中的快捷方式,所谓下标脚本语法就是能够通过,实例[索引值]来访问实例中的数据,类似于我们访问数组和字典,其实Swift中的数组和字典是一个结构体
Array:public subscript(index: Int) -> Element
arr[0] == arr.subscript(0)
Dictionary:public subscript(key: Key) -> Value?
dict["key"] == dict.subscript("key")
使用案列
struct Student {
var name:String = "xiaoming"
var math:Double = 99.0
var chinese:Double = 99.0
var english:Double = 99.0
func score(course:String) ->Double?
{
switch course{
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
//要想实现下标访问, 必须实现subscript方法
subscript(course:String) ->Double?{
//如果想要通过下标访问, 必须实现get方法
get{
switch course{
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
//如果想要通过下表赋值, 必须实现set方法
set{
switch course{
case "math":
math = newValue!// 因为返回的是可选类型,所以使用了强制解包
case "chinese":
chinese = newValue!
case "english":
english = newValue!
default:
print("not found")
}
}
}
}
var stu = Student(name: "zs", math: 99.0, chinese: 88.0, english: 10.0)
print(stu.score(course: "math") ?? "nil")
stu["chinese"] = 100.0
print(stu["chinese"]!)
Swift中允许多索引的下标的
struct Mul {
subscript(a:Int, b:Int,c:Int) -> Int
{
return a * b * c
}
}
var m = Mul()
print(m[3, 5,10]) //150
网友评论