微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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("36倍是\(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

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

"a"2) //"美国\n"

3) //"未知国家\n"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐