您的位置:首页 > 移动开发 > Swift

swift - 为类和结构体增加下标(subscript)操作

2016-04-28 16:28 435 查看
数组(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倍是18\n"

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

print(country["c",1])
//"中国\n"

print(country["a",2])
//"美国\n"

print(country["a",3])
//"未知国家\n"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: