swift - 为类和结构体增加下标(subscript)操作
数组(Array)和字典(NSDictionary)都是struct类型,而且都支持下标操作。 类,也支持下标操作。
1.struct类型的设置 struct TimesTable2 { let multiplier:Int subscript(index:Int) -> Int{
return multiplier * index } } let threeTimesTable2 = TimesTable2(multiplier:3) //TimesTable2 print("3的6倍是(threeTimesTable2[6])") //"3的6倍是18n" 2.class类型的设置 class MySubscript{ subscript(key1:String,key2:Int)->String{
if key1 == "c" && key2 == 1{
return "中国" }else if key1 == "a" && key2 == 2{
return "美国" }else{
return "未知国家" } } } var country = MySubscript() //MySubscript (country["c",1]) //"中国n" "a"2) //"美国n" 3) //"未知国家n" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |