本文主要是介绍Swift --- 下标(subscript),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.subscript可以给任意类型(class/struct/enum)添加下标功能
2..subscript中定义的返回值类型决定了
get方法的返回值类型
set方法中newValue的类型
3.subscript可以接受多个参数,并且类型任意
subscrip(v1: Int, v2: Int) -> Int
4.subscript可以没有set方法,但必须要有get方法
5.subscript可以设置参数标签
subscript(index i: Int) -> Double
6.subscript可以是类型方法
static subscript(index: Int) -> Double
例:
class Point {var x = 0.0, y = 0.0subscript(index: Int) -> Double {set {if index == 0 {x = newValue} else if index == 1 {y = newValue}}get {if index == 0 {return x} else if index == 1 {return y}return 0}}
}
var p = Point()
p[0] = 11.1
p[1] = 22.2
print(p.x) //11.1
print(p.y) //22.2
print(p[0]) //11.1
print(p[1]) //22.2
和nonmutating组合应用:
protocol NSUserDefaultsSubscipt {subscript(key: String) -> AnyObject? { get nonmutating set }
}
extension NSUserDefaults:NSUserDefaultsSubscipt {subscript(key: String) -> AnyObject? {get { return objectForKey(key) }set { setObject(newValue, forKey: key) }}
}
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults["key"] = "value"
这篇关于Swift --- 下标(subscript)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!