1).實例方法
class MyPoint {
var x : Double = 10
func setX(newX newX : Double) { // 實例方法
x = newX
}
}
let point = MyPoint()
point.setX(newX: 10)
2).方法的參數(shù)名稱
class MyPoint {
var x : Double = 10
func setX(newX : Double , newY : Double , _ newZ : Double) { // 實例方法
x = newX + newY + newZ
}
}
let point = MyPoint()
point.setX(10, newY: 10, 11)
//調(diào)用實例方法(經(jīng)測試,現(xiàn)在版本全局方法也是如次)的時候,默認從第二個參數(shù)起,
參數(shù)的內(nèi)部參數(shù)名稱都同時作為外部參數(shù)名稱,若要不顯示外部參數(shù)名稱,
則可以使用 _
3).結(jié)構(gòu)體中的mutating方法
值類型(結(jié)構(gòu)體或者枚舉)默認方法是不可以修改屬性的,如果想要修改,
需要做特殊處理: 加關(guān)鍵字mutating
struct MyPoint {
var x : Double = 10
mutating func setX(newX : Double , newY : Double , _ newZ : Double) { // 實例方法
self.x = newX + newY + newZ
}
}
var point = MyPoint()
point.setX(10, newY: 10, 11)
4).類方法
class PointClass {
static var x = 10
var y = 10
static func pointFunc () {
print("point")
x = 10
// y = 10 y是對象成員屬性 類方法不可以訪問 只可以訪問類成員屬性
}
}
PointClass.pointFunc()
5).下標(biāo)subscripts腳本語法
所謂的下標(biāo)腳本語法,就是能夠通過 實例[索引值]來訪問實例中數(shù)據(jù)的一種快捷方式
struct Student {
var math = 0.0
var chinese = 0.0
func score(type:NSString) -> Double {
switch type {
case "math":
return math
case "chinese" :
return chinese
default :
return 0
}
}
subscript (type:NSString) -> Double { //下標(biāo)腳本語法
get {
switch type {
case "math":
return math
case "chinese" :
return chinese
default :
return 0
}
}
set {
switch type {
case "math":
math = newValue
case "chinese" :
chinese = newValue
default : break
}
}
}
}
var xioali = Student(math: 97, chinese: 89)
print(xioali["math"])
print(xioali.score("math"))
xioali["math"] = 19
print(xioali["math"])
6).subscripts多索引的實現(xiàn)
struct Mul {
subscript (a : Int , b : Int) -> Int {
return a * b
}
}
let mul = Mul()
print(mul[3,2])