Swift 基礎學習 例項方法

2021-07-10 09:48:09 字數 2623 閱讀 5717

/*

方法(1) 例項方法

(2) 方法的引數名稱

(3) 例項方法中隱藏的self

(4) mutating方法

(5) 類方法

(6) 下標指令碼語法

(7) 單索引值下標指令碼

(8) 多索引值下標指令碼

*///(1)例項方法

class mypoint

// func setx(x: double, _ y: double)

func show()

}var p0 = mypoint()

//通過例項物件呼叫方法

p0.setx(10.0, y:10.0)

p0.show()

//(2)方法的引數名稱

func setx(x: double, y: double)

setx(10, y:10)

//(3)self

class mypoint1

func show()

}var p1 = mypoint1()

p1.setx(10, y:10) //p1 == self

/*(4) mutating方法

值型別 (結構體或者列舉) 預設方法是不可以修改屬性的,如果要修改需要做特殊處理

*/class myperson

func show()

}var m0 = myperson()

m0.set(name: "frank", age:24)

m0.show()

//將class改為struct

struct myperson1

func show()

}var m1 = myperson1()

m1.set(name: "frank", age:24)

m1.show()

enum lightswitch

}}var light = lightswitch.off

light.next() //light == .low

/*(5) 型別方法

通過類名來呼叫的方法,就像型別屬性一樣.

類方法對應的關鍵字是static (結構體和列舉) class (類)

類方法裡面不存在self

*/struct typemethods

//類方法裡面不可以訪問普通的成員變數

static func staticmethod()

}var tm = typemethods()

tm.method()

typemethods.staticmethod()

//跟結構體一樣

class typemethods1

//類方法裡面不可以訪問普通的成員變數

class func staticmethod()

}var tm1 = typemethods1()

tm1.method()

typemethods1.staticmethod()

/*(6)subscripts(下標)-訪問物件中資料的快捷方式

所謂下標指令碼語法就是能夠通過 例項[索引值]來訪問例項中的資料

subscript (index: int) -> element //陣列

subscript (key: key) -> value? //字典

dict[key]

dict.subscript(key)

array[10]

array.subscript(10)

*/let array = [1

,3,5

,6]print(array[2]) // 例項物件[索引] subscripts

let dict = ["1"

:1] // key:value , key hash

print(dict["1"]) //

let array1:array= [1

,3,5

,6]print(array1[2]) // 例項物件[索引] subscripts

let dict1:dictionary= ["1"

:1] // key:value , key hash

print(dict1["1"])

/*(7)subscript方法實現

*/struct student

}//想要實現下標訪問時需要實現自己定義的乙個subscript

subscript (course: string) -> int?

}set }}

}var frackchun = student(math:98, chinese:94, english:45)

//frackchun["math"] frackchun.scoreof("math")

//想要修改的話要實現setter方法

frackchun["math"] =99

print(frackchun.scoreof("math"))

print(frackchun["math"])

/*(8)多索引subscript

*/struct mul

}var mul = mul()

print(mul[3,5])

Swift 例項方法

例項方法 1 例項方法 print 1 例項方法 class mypoint func showpoint func setpoint x double,y double 預設第一引數作為內部引數,第二個及以後既作為內部有作為外部引數 setpoint x 10.0,10.0 var p0 mypo...

Swift 例項方法和型別方法

歡迎 大家對 例項方法和型別方法 的概念應該不陌生了,在objective c中很常見。例如 1.例項方法 減號開頭 instancetype init 呼叫的時候,必須先進行例項化乙個物件 alloc 然後呼叫init方法。2.型別方法 加號開頭 void animatewithduration ...

Swift基礎學習

swift基礎學習 這個 最近看了一下,對於基本語法解釋概括的相對全面,如同重新練習一遍oc似的,挺全面的,謝謝原文 1 陣列內容型別鎖定時 原文方法 var strarray string 我是 字串的陣列 現在方法 var strarray string 我是 字串的陣列 當然 var stra...