一.Swift函數的基本寫法
func sayHello(name:String) -> String {
let result = "Hello," + name + "!"
return result
}
sayHello(name: "Sunshine") // 函數返回的結果是:Hello,Sunshine!
// 函數名:sayHello
// 參數列表:name - 參數名 String - 參數類型
// 返回值:String - 返回值的參數類型
因為 name
有可能為nil
,所以函數的name
應該是可選類型:
func sayHello(name:String?) -> String {
let result = "Hello," + (name ?? "Guest") + "!"
return result
}
var nickname:String?
nickname = "Sunshine"
print(sayHello(name: nickname))
二.使用元組返回多個值
// 返回值不一定要給返回的名字的 但是還是建議加上 增強代碼的可讀性
var userScores:[Int] = [12,999,666,7687,9999,1024,2567]
func maxmainScores(scores:[Int]) -> (maxScores:Int, mainScores:Int)? {
// 在實際項目中 讀取到的數組userScores可能為nil 所以函數返回的元組也是一個可選類型 如果數組為nil,就return nil
if scores.isEmpty {
return nil
}
var maxScore = scores[0], minScore = scores[0]
for score in scores {
maxScore = max(maxScore, score)
minScore = min(minScore, score)
}
return(maxScore,minScore)
}
print("測試 - \(maxmainScores(scores: userScores))") // 打印的結果:測試 - (maxScores: 9999, mainScores: 12)
Q:在實際開發中可能會遇到userScores沒有數據就返回nil的情況,該如何改進程序?
var userScores:[Int]? = [12,999,666,7687,9999,1024,2567]
userScores = userScores ?? []
func maxmainScores(scores:[Int]) -> (maxScores:Int, mainScores:Int)? {
if scores.isEmpty {
return nil
}
var maxScore = scores[0], minScore = scores[0]
for score in scores {
maxScore = max(maxScore, score)
minScore = min(minScore, score)
}
return(maxScore,minScore)
}
print("測試 - \(maxmainScores(scores: userScores!))") // 打印的結果:測試 - (maxScores: 9999, mainScores: 12)
三. 參數的默認值
// 在參數類型后面加上: ‘ ="Hello"’表示greeting這個參數默認值為Hello 調用的時候去掉greeting參數即可。
func sayHello(name:String,greeting:String = "Hello",others:String) -> String {
let result = greeting + "," + name + others + "!"
return result
}
print("測試 - \( sayHello(name: "Sunshine", others: " And Candy"))")
四.可變參數
// Others:Int...:表示可以傳任意多個參數 一個函數只能有一個可變參數
func add(a:Int, b:Int, Others:Int...) -> Int {
var result = a + b
for number in Others {
result += number
}
return result
}
var result0 = add(a: 1, b: 2, Others: 3,4,5)
var result1 = add(a: 1, b: 2)
print("測試 - \(result1)")
五.常量參數、變量參數和inout參數
Q:如何把十進制的數據轉化成二進制的數據,并且以字符串的形式打印出來?
func toBinary(num:Int) -> String {
var num = num
var result:String = ""
while num != 0 {
result = String(num%2) + result
num = num/2
}
return result
}
let result = toBinary(num: 6)
print("測試 - \(result)") // 打印結果是:110
Q:如何交換兩個變量?
func swapTwoInts( a:inout Int, b:inout Int) {
var c = a
a = b
b = c
}
var x = 10, y = 8
swapTwoInts(a: &x, b: &y)
print("測試 - \(x,y)") // 最后的打印結果:測試 - (8, 10)
// inout:告訴系統我傳入的參數不是要存入副本的 而是實實在在改變它的值的 相當于C語言里面的址傳遞
等價于:
var x = 10, y = 8
swap(&x, &y)
print("測試 - \(x,y)") // 最后的打印結果:測試 - (8, 10)
六.函數類型
func add(a:Int, b:Int) -> Int {
return a + b
}
let anotherAdd:(Int,Int) -> Int = add // 讓一個常量為函數類型
print("測試 - \(anotherAdd(Int(4.0), 6))")
func sayHello(nickName:String){
print("Hello," + nickName)
}
let anotherSayHello:(String)->() = sayHello
anotherSayHello("Sunshine")
func sayHi(){
print("Sunshine")
}
let anotherSayHi:()->() = sayHi
anotherSayHi()
Q: 如何定義函數的類型?
// 有參數值 有函數有返回值
let anotherAdd:(Int,Int) -> Int = add
// 有參數值 沒有函數返回值 ->()不能省略
let anotherSayHello:(String)->() = sayHello
//沒有參數值 沒有函數返回值
let anotherSayHi:()->() = sayHi
//沒有參數值 沒有函數返回值
let anotherSayHi:()->Void = sayHi
栗子:
func changeScores(op:(Int) -> Int,scores:inout [Int]) {
for i in 0..<scores.count {
scores[i] = op(scores[i])
}
}
func op1(x:Int)->Int {
return Int(sqrt(Double(x))*10)
}
func op2(x:Int)->Int {
return Int(Double(x)/150.0 * 100.0)
}
func op3(x:Int)->Int {
return x + 3
}
var scores1 = [36,61,78,89,99]
changeScores(op: op1, scores: &scores1)
print("測試 - \(scores1)") // 測試 - [60, 78, 88, 94, 99]
var scores2 = [88,99,108,128,150]
changeScores(op: op2, scores: &scores2)
print("測試 - \(scores2)") // 測試 - [58, 66, 72, 85, 100]
var scores3 = [59,60,77,87,95]
changeScores(op: op3, scores: &scores3)
print("測試 - \(scores3)") // 測試 - [62, 63, 80, 90, 98]
七.閉包的基本語法
var arr = [1,3,5,7,9,8,10,0]
arr.sort() // 無返回值 此時的arr已經按照從小到大的順序排列
arr.sorted() // 有返回值 返回的結果即是從小到大的順序排列之后的數組
// 閉包的寫法
{(a:Int,b:Int) -> Bool in
// 具體要執行的代碼 Bool表示返回值
}
栗子:
var strArr = ["d","cd","bcd","abcd","ab","a"]
strArr.sort { (str1, str2) -> Bool in
if(str1.characters.count != str2.characters.count) {
return str1.characters.count < str2.characters.count
}
return str1 < str2
}
print("測試 - \(strArr)") // 打印結果:測試 - ["a", "d", "ab", "cd", "bcd", "abcd"]
八.使用閉包簡化語法
var arr = [1,3,5,7,9,8,10,0]
func compareTwoInts(a:Int,b:Int) -> Bool {
return a > b
}
//arr.sort { (a, b) -> Bool in return a > b}
//print("測試 - \(arr)")
// 簡化寫法1:(閉包里面的邏輯只有一句話的時候才可以這么省略)
arr.sort { a, b in return a > b}
print("測試 - \(arr)")
// 簡化寫法2:
arr.sort { a, b in a > b}
print("測試 - \(arr)")
九.值類型和引用類型
func tryToChangeValue( x :Int) {
var x = x
x += 1
}
var num = 6
tryToChangeValue(x: num) // x = 6 沒發生變化 說明是值類型
引用類型:function(函數)/closure(閉包)
func calcTotalMiles(todayMiles:Int) -> () -> Int {
var totalMiles = 0
return {
totalMiles += todayMiles
return totalMiles
}
}
栗子:
var dailyTwoMiles = calcTotalMiles(todayMiles: 10)
dailyTwoMiles() // 10
let result = dailyTwoMiles() // 20
print("測試 - \(result)") // 20
var myplan = dailyTwoMiles
let myresult1 = myplan()
print("測試 - \(myresult1)")// 30
dailyTwoMiles()
let myresult2 = myplan()
print("測試 - \(myresult2)")// 50 myplan發生了改變 說明是引用類型
十.枚舉的基本用法
enum gameEnding {
case Win
case Lose
case Draw
}
var yourScore = 100
var enemyScore = 100
var theGameEnding:gameEnding
if yourScore > enemyScore {
theGameEnding = gameEnding.Win
}else if yourScore == enemyScore {
theGameEnding = .Draw
}else {
theGameEnding = .Lose
}
switch theGameEnding {
case .Win:
print("測試 - Win")
case .Lose:
print("測試 - Lose")
case .Draw:
print("測試 - Draw")
}
十一.枚舉類型關聯默認值
enum Months:Int {
case Jan = 1,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
}
let curMonth:Months = .Nov
let rawValue = curMonth.rawValue
print("測試 - \(rawValue)") // 11
let nextMonth:Months? = Months.init(rawValue: 12)
print("測試 - \(nextMonth!.rawValue)") // 12
十二.更加靈活的枚舉使用方式:枚舉里面可以存儲不同類型的值
enum barCode {
case UPCA(Int,Int,Int,Int)
case QRCode(String)
}
let proCodeA = barCode.UPCA(4, 102, 345, 6)
let proCodeB:barCode = .QRCode("This is a informaton")
switch proCodeA {
case .UPCA(let number1, let number2, let number3, let number4):
print("測試 - \(number1)\(number2)\(number3)\(number4)")
default:
print("測試 - This is an information")
}