最近項(xiàng)目使用的是OC,后頭看之前用Swift開發(fā)的一個(gè)項(xiàng)目時(shí),發(fā)現(xiàn)很多細(xì)節(jié)都忘記了????。
為了回憶和以后方便查看,現(xiàn)在根據(jù)官方文檔swift編程語(yǔ)言,做下筆記。
一、函數(shù)
1、無(wú)參數(shù)函數(shù)
func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
// 打印 "hello, world"
2、多參數(shù)函數(shù)
func greet(person: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return greetAgain(person: person)
} else {
return greet(person: person)
}
}
print(greet(person: "Tim", alreadyGreeted: true))
// 打印 "Hello again, Tim!"
3、無(wú)返回值函數(shù)
func greet(person: String) {
print("Hello, \(person)!")
}
greet(person: "Dave")
// 打印 "Hello, Dave!"
4、多重返回值函數(shù)
minMax(array:) 函數(shù)返回一個(gè)包含兩個(gè) Int 值的元組,這些值被標(biāo)記為 min 和 max ,以便查詢函數(shù)的返回值時(shí)可以通過(guò)名字訪問(wèn)它們。
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
5、可選元組返回類型
如果函數(shù)返回的元組類型有可能整個(gè)元組都“沒(méi)有值”,你可以使用可選的( optional ) 元組返回類型反映整個(gè)元組可以是nil的事實(shí)。你可以通過(guò)在元組類型的右括號(hào)后放置一個(gè)問(wèn)號(hào)來(lái)定義一個(gè)可選元組
func minMax(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
使用可選綁定來(lái)檢查 minMax(array:) 函數(shù)返回的是一個(gè)存在的元組值還是 nil
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
// 打印 "min is -6 and max is 109"
6、函數(shù)參數(shù)標(biāo)簽和參數(shù)名稱
每個(gè)函數(shù)參數(shù)都有一個(gè)參數(shù)標(biāo)簽( argument label )以及一個(gè)參數(shù)名稱( parameter name )。
參數(shù)標(biāo)簽在調(diào)用函數(shù)的時(shí)候使用;
參數(shù)名稱在函數(shù)的實(shí)現(xiàn)中使用。
默認(rèn)情況下,函數(shù)參數(shù)使用參數(shù)名稱來(lái)作為它們的參數(shù)標(biāo)簽。
-
指定參數(shù)標(biāo)簽
在參數(shù)名稱前指定它的參數(shù)標(biāo)簽,中間以空格分隔:
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// 打印 "Hello Bill! Glad you could visit from Cupertino."
-
忽略參數(shù)標(biāo)簽
如果你不希望為某個(gè)參數(shù)添加一個(gè)標(biāo)簽,可以使用一個(gè)下劃線(_)來(lái)代替一個(gè)明確的參數(shù)標(biāo)簽。
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
// 在函數(shù)體內(nèi),firstParameterName 和 secondParameterName 代表參數(shù)中的第一個(gè)和第二個(gè)參數(shù)值
}
someFunction(1, secondParameterName: 2)
-
默認(rèn)參數(shù)值
你可以在函數(shù)體中通過(guò)給參數(shù)賦值來(lái)為任意一個(gè)參數(shù)定義默認(rèn)值(Deafult Value)。當(dāng)默認(rèn)值被定義后,調(diào)用這個(gè)函數(shù)時(shí)可以忽略這個(gè)參數(shù)。
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// 如果你在調(diào)用時(shí)候不傳第二個(gè)參數(shù),parameterWithDefault 會(huì)值為 12 傳入到函數(shù)體中。
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12
-
可變參數(shù)
一個(gè)可變參數(shù)(variadic parameter)可以接受零個(gè)或多個(gè)值。
函數(shù)調(diào)用時(shí),你可以用可變參數(shù)來(lái)指定函數(shù)參數(shù)可以被傳入不確定數(shù)量的輸入值。
通過(guò)在變量類型名后面加入(...)的方式來(lái)定義可變參數(shù)。
一個(gè)函數(shù)最多只能擁有一個(gè)可變參數(shù)。
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// 返回 3.0, 是這 5 個(gè)數(shù)的平均數(shù)。
arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是這 3 個(gè)數(shù)的平均數(shù)。
7、函數(shù)類型
函數(shù)的類型由函數(shù)的參數(shù)類型和返回類型組成。
例如:
這個(gè)函數(shù)的類型是 (Int, Int) -> Int,“這個(gè)函數(shù)有兩個(gè) Int 型的參數(shù)并返回一個(gè) Int 型的值?!薄?/p>
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
-
函數(shù)類型作為參數(shù)類型
可以用 (Int, Int) -> Int 這樣的函數(shù)類型作為另一個(gè)函數(shù)的參數(shù)類型。這樣你可以將函數(shù)的一部分實(shí)現(xiàn)留給函數(shù)的調(diào)用者來(lái)提供。
var mathFunction: (Int, Int) -> Int = addTwoInts
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// 打印 "Result: 8"
-
函數(shù)類型作為返回類型
可以用函數(shù)類型作為另一個(gè)函數(shù)的返回類型。你需要做的是在返回箭頭(->)后寫一個(gè)完整的函數(shù)類型。
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
//用 chooseStepFunction(backward:) 來(lái)獲得兩個(gè)函數(shù)其中的一個(gè)
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 現(xiàn)在指向 stepBackward() 函數(shù)。
-
嵌套函數(shù)
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}
2、枚舉
不必給每一個(gè)枚舉成員提供一個(gè)值。如果給枚舉成員提供一個(gè)值(稱為“原始”值),則該值的類型可以是字符串,字符,或是一個(gè)整型值或浮點(diǎn)數(shù)。
-
創(chuàng)建枚舉
使用enum關(guān)鍵詞來(lái)創(chuàng)建枚舉并且把它們的整個(gè)定義放在一對(duì)大括號(hào)內(nèi):
enum SomeEnumeration {
// 枚舉定義放在這里
}
注意與 C 和 Objective-C 不同,Swift 的枚舉成員在被創(chuàng)建時(shí)不會(huì)被賦予一個(gè)默認(rèn)的整型值。
例如:下面的枚舉,north,south,east和west不會(huì)被隱式地賦值為0,1,2和3。相反,這些枚舉成員本身就是完備的值,這些值的類型是已經(jīng)明確定義好的CompassPoint類型。
enum CompassPoint {
case north
case south
case east
case west
}
-
關(guān)聯(lián)值
可以定義 Swift 枚舉來(lái)存儲(chǔ)任意類型的關(guān)聯(lián)值,每個(gè)枚舉成員的關(guān)聯(lián)值類型可以各不相同。
這能讓你連同成員值一起存儲(chǔ)額外的自定義信息,并且你每次在代碼中使用該枚舉成員時(shí),還可以修改這個(gè)關(guān)聯(lián)值。
例如:
1、定義一個(gè)名為Barcode的枚舉類型,它的一個(gè)成員值是具有(Int,Int,Int,Int)類型關(guān)聯(lián)值的upc,另一個(gè)成員值是具有String類型關(guān)聯(lián)值的qrCode。
使用如下方式定義表示兩種商品條形碼的枚舉:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
這個(gè)定義不提供任何Int或String類型的關(guān)聯(lián)值,它只是定義了,當(dāng)Barcode常量和變量等于Barcode.upc或Barcode.qrCode時(shí),可以存儲(chǔ)的關(guān)聯(lián)值的類型。
2、然后可以使用任意一種條形碼類型創(chuàng)建新的條形碼,例如:
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
上面的例子創(chuàng)建了一個(gè)名為productBarcode的變量,并將Barcode.upc賦值給它,關(guān)聯(lián)的元組值為(8, 85909, 51226, 3)。
3、同一個(gè)商品可以被分配一個(gè)不同類型的條形碼,例如:
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
這時(shí),原始的Barcode.upc和其整數(shù)關(guān)聯(lián)值被新的Barcode.qrCode和其字符串關(guān)聯(lián)值所替代。Barcode類型的常量和變量可以存儲(chǔ)一個(gè).upc或者一個(gè).qrCode(連同它們的關(guān)聯(lián)值),在同一時(shí)間只能存儲(chǔ)這兩個(gè)值中的一個(gè)。
4、使用一個(gè) switch 語(yǔ)句來(lái)檢查不同的條形碼類型,關(guān)聯(lián)值可以被提取出來(lái)作為 switch 語(yǔ)句的一部分,每個(gè)關(guān)聯(lián)值作為一個(gè)常量(用let前綴)或者作為一個(gè)變量(用var前綴)來(lái)使用
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
// 打印 "QR code: ABCDEFGHIJKLMNOP."
5、如果一個(gè)枚舉成員的所有關(guān)聯(lián)值都被提取為常量,或者都被提取為變量,為了簡(jiǎn)潔,你可以只在成員名稱前標(biāo)注一個(gè)let或者var:
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// 輸出 "QR code: ABCDEFGHIJKLMNOP."
-
原始值的隱式賦值
在使用原始值為整數(shù)或者字符串類型的枚舉時(shí),不需要顯式地為每一個(gè)枚舉成員設(shè)置原始值,Swift 將會(huì)自動(dòng)為你賦值。
1、當(dāng)使用整數(shù)作為原始值時(shí),隱式賦值的值依次遞增1。如果第一個(gè)枚舉成員沒(méi)有設(shè)置原始值,其原始值將為0。
enum Planet: Int {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
2、當(dāng)使用字符串作為枚舉類型的原始值時(shí),每個(gè)枚舉成員的隱式原始值為該枚舉成員的名稱。
enum CompassPoint: String {
case north, south, east, west
}
CompassPoint.south擁有隱式原始值south,依次類推。
-
遞歸枚舉
遞歸枚舉是一種枚舉類型,它有一個(gè)或多個(gè)枚舉成員使用該枚舉類型的實(shí)例作為關(guān)聯(lián)值。使用遞歸枚舉時(shí),編譯器會(huì)插入一個(gè)間接層。你可以在枚舉成員前加上indirect來(lái)表示該成員可遞歸。
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
也可以在枚舉類型開頭加上indirect關(guān)鍵字來(lái)表明它的所有成員都是可遞歸的:
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
解釋:
上面定義的枚舉類型可以存儲(chǔ)三種算術(shù)表達(dá)式:純數(shù)字、兩個(gè)表達(dá)式相加、兩個(gè)表達(dá)式相乘。枚舉成員addition和multiplication的關(guān)聯(lián)值也是算術(shù)表達(dá)式——這些關(guān)聯(lián)值使得嵌套表達(dá)式成為可能。
使用:計(jì)算(5 + 4) * 2
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product))
// 打印 "18"