加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 07:02:55 所属栏目:百科 来源:网络整理
导读:数组(Array)和字典(NSDictionary)都是struct类型,而且都支持下标操作。 类,也支持下标操作。 1.struct类型的设置 struct TimesTable2 { let multiplier: Int subscript (index: Int ) - Int { return multiplier * index } } let threeTimesTable2 = T

数组(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倍是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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读