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"
类,也支持下标操作。
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"
相关文章推荐
- iOS swift运算符详解
- swift2.0 学习笔记six
- iOS swift 使用基本语法
- Swift - Struct 与Class 的差异性
- Swift快速入门之协议与扩展
- 对照Java学习Swift--类和结构体(Classes and Structures)
- swift的基本语法
- swift入门学习
- Swift中的通知
- iOS学习笔记45-Swift(五)协议
- iOS学习笔记45-Swift(五)协议
- Swift之逻辑分支&循环的介绍
- iOS Swift&OC 模仿主流App 实现滑动视图隐藏导航栏
- Swift/OC 为View或ImageView设置聊天气泡的小三角
- swift 中运算符空格规则,as? 操作符
- swift2.0 学习笔记five
- Swift数据类型之整型和浮点型-备
- swift - 类型方法(即静态变量)
- Swift UITableViewCell中的按钮点击事件
- swift - mutating(杖举或结构体,通过方法来改变自身的值)