# Swift方法
在 Swift 中特定類型的相關(guān)聯(lián)功能被稱為方法作媚。在 Objective C 中類是用來定義方法差购,其中作為 Swift 語言為用戶提供了靈活性,類西饵,結(jié)構(gòu)和枚舉中可以定義使用方法典奉。
####實例方法
在 Swift 語言躺翻,類,結(jié)構(gòu)和枚舉實例通過實例方法訪問卫玖。
**實例方法提供的功能**
- 訪問和修改實例屬性
- 函數(shù)關(guān)聯(lián)實例的需要
實例方法可以寫在花括號 {} 內(nèi)公你。它隱含的訪問方法和類實例的屬性。當該類型指定具體實例它調(diào)用獲得訪問該特定實例骇笔。
語法
func funcname(Parameters)-> returntype
{
Statement1Statement2---Statement N
return parameters
}
示例
class calculations {
let a:Intlet b:Intlet res:Int
init(a:Int, b:Int){self.a = a
self.b = b
res = a + b
}
func tot(c:Int)->Int{
return res - c
}
func result(){
println("Result is: \(tot(20))")
println("Result is: \(tot(50))")
}
}
let pri = calculations(a:600, b:300)
pri.result()
當我們使用 playground 運行上面的程序省店,得到以下結(jié)果
Result is: 880
Result is: 850
`Calculations` 類定義了兩個實例方法:
init() 被定義為兩個數(shù) a 和 b 相加,并將其結(jié)果存儲在'res'
tot() 用于通過從 “res” 值減去 'c'
最后笨触,調(diào)用打印的計算a和b的值方法. 實例方法以 "." 語法訪問
####局部和外部參數(shù)名稱
Swift 函數(shù)描述了局部和全局變量聲明懦傍。同樣,Swift 方法的命名規(guī)則也類似 Objective C芦劣。但是局部和全局參數(shù)名稱聲明的特性對于函數(shù)和方法不同粗俱。 swift 第一個參數(shù)是由介詞名稱'with', 'for' 和 'by' 訪問命名規(guī)則。
Swift 提供聲明作為局數(shù)參數(shù)名稱虚吟,其它參數(shù)名稱為全局參數(shù)名寸认,第一參數(shù)是方法名稱。在這里串慰,“no1”方法作為局部參數(shù)名來聲明偏塞。 'no2' 用于全局聲明,并通過該程序訪問邦鲫。
class division {var count:Int=0
func incrementBy(no1:Int, no2:Int){
count = no1 / no2
println(count)
}
}
let counter = division()
counter.incrementBy(1800, no2:3)
counter.incrementBy(1600, no2:5)
counter.incrementBy(11000, no2:3)
當我們使用 playground 運行上面的程序灸叼,得到以下結(jié)果
600
320
3666
外部參數(shù)名稱使用 # 和 _ 符號
盡管 Swift 方法提供第一個參數(shù)名稱作為局部聲明,用戶必須提供以修改參數(shù)名稱從局部到全局聲明庆捺。這可以通過'#'符號前綴使用第一參數(shù)名來完成古今。通過這樣做,第一參數(shù)可以作為全局在整個模塊訪問滔以。
當用戶需要使用外部名稱訪問在后面的參數(shù)名中捉腥,方法的名字使用“_”符號覆蓋。
class multiplication {
var count:Int=0
func incrementBy(#no1:Int, no2:Int){
count = no1 * no2
println(count)
}
}
let counter = multiplication()
counter.incrementBy(no1:800, no2:3)
counter.incrementBy(no1:100, no2:5)
counter.incrementBy(no1:15000, no2:3)
當我們使用 playground 運行上面的程序你画,得到以下結(jié)果
2400
500
45000
在方法中的Self屬性
方法有一個隱式屬性被稱為“self”抵碟,所有定義的類型實例所都有桃漾。“self”屬性被用于表示當前的實例定義的方法立磁。
class calculations {
let a:Intlet b:Intlet res:Int
init(a:Int, b:Int){self.a = a
self.b = b
res = a + b
println("Inside Self Block: \(res)")}
func tot(c:Int)->Int{return res - c
}
func result(){
println("Result is: \(tot(20))")
println("Result is: \(tot(50))")
}
}
let pri = calculations(a:600, b:300)
let sum = calculations(a:1200, b:300)
pri.result()
sum.result()
當我們使用 playground 運行上面的程序呈队,得到以下結(jié)果
Inside Self Block: 900
Inside Self Block: 1500
Result is: 880
Result is: 850
Result is: 1480
Result is: 1450
####修改的實例方法值類型
在 Swift 語言結(jié)構(gòu)和枚舉和值類型不能由它的實例方法來改變剥槐。然而唱歧,swift 語言通過“變異”行為提供了靈活修改值類型。突變將使得在實例方法中的任何變化粒竖,將方法執(zhí)行之后變化返回到原來的形式颅崩。此外,由 “selft” 屬性的新實例其隱式函數(shù)創(chuàng)建蕊苗,執(zhí)行之后將取代現(xiàn)有的方法
struct area {
var length =1var breadth =1
func area()->Int{
return length * breadth
}
mutating func scaleBy(res:Int){
length *= res
breadth *= res
println(length)
println(breadth)
}
}
var val = area(length:3, breadth:5)
val.scaleBy(3)
val.scaleBy(30)
val.scaleBy(300)
當我們使用 playground 運行上面的程序沿后,得到以下結(jié)果
9
15
270
450
81000
135000
Self 屬性的不同誘變方法
突變方法結(jié)合 “self” 屬性分配給新實例所定義的方法。
struct area {
var length =1var breadth =1
func area()->Int{return length * breadth
}
mutating func scaleBy(res:Int){self.length *= res
self.breadth *= res
println(length)
println(breadth)}}var val = area(length:3, breadth:5)
val.scaleBy(13)
當我們使用 playground 運行上面的程序朽砰,得到以下結(jié)果
39
65
##類型方法
當方法的特定實例調(diào)用尖滚,它調(diào)用一個實例方法并且當方法調(diào)用特定類型的方法的一個被定義為 "類型方法“。類型方法 “類” 是由“func”關(guān)鍵字和結(jié)構(gòu)定義,和枚舉型方法使用 “func” 關(guān)鍵字之前的“static”關(guān)鍵字定義瞧柔。
類型方法調(diào)用漆弄,是通過訪問 '.' 而不是調(diào)用特定實例的方法,例子和語法如下:
classMath{
class func abs(number:Int)->Int{
if number <0{
return(-number)
}else{
return number
}
}
}
struct absno {
static func abs(number:Int)->Int{
if number <0{
return(-number)
}else{
return number
}
}
}
letno=Math.abs(-35)let num = absno.abs(-5)
println(no)
println(num)
當我們使用 playground 運行上面的程序造锅,得到以下結(jié)果
35
5
# Swift下標
訪問一個集合的元素成員撼唾,在類中的序列和列表,結(jié)構(gòu)和枚舉都可以使用下標哥蔚。這些下標用于存儲和使用索引來檢索值倒谷。數(shù)組元素可使用如:`someArray[index]`,在 Dictionary 實例及其后續(xù)成員元素的訪問也可以使用如:`someDicitonary[key]`糙箍。
對于單一類型渤愁,下標范圍可以從單一到多個聲明。我們可以用適當?shù)南聵酥剌d傳遞給下標索引值的類型深夯。下標也可以根據(jù)輸入數(shù)據(jù)類型聲明范圍從單一維度到多維度抖格。
####下標聲明語法和用法
讓我們回顧一下計算屬性。下標也遵循計算屬性相同的語法塌西。對于查詢類型的實例下標括在方括號內(nèi)他挎,接著是實例名稱。下標語法遵循結(jié)構(gòu)作為 “實例方法” 和 “計算屬性” 相同的語法捡需。`“subscript”` 關(guān)鍵字用來定義標办桨,用戶可以指定一個或多個參數(shù),它們帶有返回類型站辉。下標可以有讀寫或只讀屬性和實例存儲和檢索使用 `“getter”` 和 `“setter”` 屬性作為計算屬性呢撞。
####語法
subscript(index:Int)->Int{
get{
// used for subscript value declarations
}
set(newValue){
// definitions are written here
}
}
**示例1**
struct subexample {
let decrementer:Int
subscript(index:Int)->Int{
return decrementer / index
}
}
let division = subexample(decrementer:100)
println("The number is divisible by \(division[9]) times")
println("The number is divisible by \(division[2]) times")
println("The number is divisible by \(division[3]) times")
println("The number is divisible by \(division[5]) times")
println("The number is divisible by \(division[7]) times")
當我們使用 playground 運行上面的程序损姜,得到以下結(jié)果
The number is divisible by 11 times
The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 20 times
The number is divisible by 14 times
**示例2**
class daysofaweek {
private var days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","saturday"]
subscript(index:Int)->String{
get{
return days[index]
}
set(newValue){
self.days[index]= newValue
}
}
}
var p = daysofaweek()
println(p[0])
println(p[1])
println(p[2])
println(p[3])
當我們使用 playground 運行上面的程序,得到以下結(jié)果
Sunday
Monday
Tuesday
Wednesday
####下標選項
下標采用單一到多元的輸入?yún)?shù)殊霞,這些輸入?yún)?shù)也屬于任意數(shù)據(jù)類型摧阅。還可以使用變量,可變參數(shù)的參數(shù)绷蹲。下標不能提供缺省參數(shù)值棒卷,或使用任何 `in-out` 參數(shù)。
定義多個標被稱為`下標重載`在一個類 或結(jié)構(gòu)體根據(jù)需要可以提供多個下標定義祝钢。這些多個標是基于被下標括號內(nèi)聲明值的類型推斷比规。
structMatrix{
let rows:Int, columns:Intvarprint:[Double]
init(rows:Int, columns:Int){
self.rows = rows
self.columns = columns
print=Array(count: rows * columns, repeatedValue:0.0)}
subscript(row:Int, column:Int)->Double{
get{
returnprint[(row * columns)+ column]
}
set{
print[(row * columns)+ column]= newValue
}
}
}
var mat =Matrix(rows:3, columns:3)
mat[0,0]=1.0
mat[0,1]=2.0
mat[1,0]=3.0
mat[1,1]=5.0
println("\(mat[0,0])")
println("\(mat[0,1])")
println("\(mat[1,0])")
println("\(mat[1,1])")
當我們使用 playground 運行上面的程序,得到以下結(jié)果
1.0
2.0
3.0
5.0
Swift 下標支持單參數(shù)到多參數(shù)聲明相應(yīng)數(shù)據(jù)類型拦英。該程序聲明的“矩陣”結(jié)構(gòu)為2*2維數(shù)組矩陣來存儲 “Double” 數(shù)據(jù)類型蜒什。 矩陣參數(shù)被輸入整數(shù)數(shù)據(jù)類型用來聲明行和列。
矩陣新實例是通過使行和列數(shù)來初始化創(chuàng)建的疤估,如下所示灾常。
var mat = Matrix(rows: 3, columns: 3)
矩陣值可通過傳遞行和列值到下標,通過逗號隔開铃拇,進行定義如下所示钞瀑。
mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0
# Swift數(shù)組
Swift 數(shù)組用于存儲相同類型的值的順序列表。Swift 要嚴格檢查锚贱,它不允許錯誤地在數(shù)組中存放了錯誤的類型仔戈。
如果賦值創(chuàng)建數(shù)組到一個變量,它總是可變的拧廊,這意味著可以通過添加元素來改變它监徘, 刪除或更改其項目,但如果分配一個數(shù)組常量到則該數(shù)組吧碾,則數(shù)組是不可被改變的凰盔, 也就它的大小和內(nèi)容不能被改變。
**創(chuàng)建數(shù)組**
可以使用下面的初始化程序語法來創(chuàng)建某種類型的空數(shù)組:
var someArray = [SomeType]()
下面是創(chuàng)建一個給定的大小倦春,并用初始值的數(shù)組的語法:
var someArray = [SomeType](count: NumbeOfElements, repeatedValue: InitialValue)
下面是一個例子户敬,以創(chuàng)建具有3個元素并初始值為零的 int 類型空數(shù)組:
var someInts = [Int](count: 3, repeatedValue: 0)
下面是一個創(chuàng)建三個元素的數(shù)組,并指定三個值的數(shù)組的例子:
var someInts:[Int] = [10, 20, 30]
**訪問數(shù)組**
可以使用下標語法從數(shù)組中檢索對應(yīng)值睁本,傳遞數(shù)組名后方括號內(nèi)的索引對應(yīng)的值尿庐,如下:
var someVar = someArray[index]
在這里,指數(shù)從0開始呢堰,這意味著可以使用索引0來訪問第一個元素抄瑟,第二元素可以通過使用索引1進行訪問,其它類似枉疼。讓我們來看看下面創(chuàng)建皮假,初始化和訪問數(shù)組的例子:
import Cocoa
var someInts = [Int](count: 3, repeatedValue: 10)
var someVar = someInts[0]
println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )
當上述代碼被編譯和執(zhí)行時鞋拟,它產(chǎn)生了以下結(jié)果:
Value of first element is 10
Value of second element is 10
Value of third element is 10
**修改數(shù)組**
可以使用 append()方法或加法賦值運算符(+=)將新的項目添加到數(shù)組的末尾,在這里首先創(chuàng)建一個空的數(shù)組惹资,然后添加新的元素到數(shù)組中贺纲,如下圖所示:
import Cocoa
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
var someVar = someInts[0]
println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )
當上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Value of first element is 20
Value of second element is 30
Value of third element is 40
可以通過分配一個在給定的索引處新的值修改數(shù)組的現(xiàn)有元素褪测,如在下面的例子:
import Cocoa
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
// Modify last element
someInts[2] = 50
var someVar = someInts[0]
println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )
當上述代碼被編譯和執(zhí)行時猴誊,它產(chǎn)生了以下結(jié)果:
Value of first element is 20
Value of second element is 30
Value of third element is 50
**迭代/遍歷數(shù)組**
可以使用 for-in 循環(huán)迭代級數(shù),在下面的例子是數(shù)組的整個集值汰扭,如下圖所示:
import Cocoa
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs += ["Google"]
for item in someStrs {
println(item)
}
當上述代碼被編譯和執(zhí)行時稠肘,它產(chǎn)生了以下結(jié)果:
Apple
Amazon
也可以使用 enumerate() 函數(shù)福铅,如下面的例子所示萝毛,它返回索引及對應(yīng)的值:
import Cocoa
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs += ["Google"]
for (index, item) in someStrs.enumerate {
println("Value at index = \(index) is \(item)")
}
當上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google
兩個數(shù)組相加
使用加法運算符(+)滑黔,以添加的相同類型的數(shù)組笆包,這將產(chǎn)生新的數(shù)組是來自兩個數(shù)組值相加組合后的數(shù)組,如下:
import Cocoa
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = intsA + intsB
for item in intsC {
println(item)
}
當上述代碼被編譯和執(zhí)行時略荡,它產(chǎn)生了以下結(jié)果:
2
2
1
1
1
**count 屬性**
可以使用只讀計算 (count) 數(shù)組屬性庵佣,找出下面顯示出數(shù)組中元素的個數(shù):
import Cocoa
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = intsA + intsB
println("Total items in intsA = \(intsA.count)")
println("Total items in intsB = \(intsB.count)")
println("Total items in intsC = \(intsC.count)")
當上述代碼被編譯和執(zhí)行時,它產(chǎn)生了以下結(jié)果:
Total items in intsA = 2
Total items in intsB = 3
Total items in intsC = 5
**空屬性**
使用只讀數(shù)組的空屬性(isEmpty)找出一個數(shù)組是否為空汛兜,如下圖所示:
import Cocoa
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = [Int]()
println("intsA.isEmpty = \(intsA.isEmpty)")
println("intsB.isEmpty = \(intsB.isEmpty)")
println("intsC.isEmpty = \(intsC.isEmpty)")
當上述代碼被編譯和執(zhí)行時巴粪,它產(chǎn)生了以下結(jié)果:
intsA.isEmpty = false
intsB.isEmpty = false
intsC.isEmpty = true