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

149 篇文章 0 订阅
33 篇文章 0 订阅

数组(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

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

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

print(country["a",3]) //"未知国家\n"



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值