Swift-函數(shù)

e.g.1

func sayHello(name: String?) -> String {
  return "Hello" + name ?? "guest"
}
var nickname: String? = nil
sayHello(name: nickname)

e.g.2: 使用元組返回多個(gè)值

func findMaxAndMin(numbers: [Int]) -> (max: Int, min: Int)? {
    
//    當(dāng)數(shù)組為空的時(shí)候,返回nil
//    if numbers.isEmpty {
//        return nil
//    }
    
    
    guard numbers.count > 0 else {
        return nil
    }
    
    var maxValue = numbers[0]
    var minValue = numbers[0]
    
    for number in numbers {
        maxValue = maxValue > number ? maxValue : number
        minValue = minValue < number ? minValue : number
    }
    
    return (maxValue, minValue)
    
}

var scores: [Int]? = [202, 1234, 5659, 982, 555]
scores = scores ?? [] //如果是nil直接賦一個(gè)空數(shù)組

if let result = findMaxAndMin(numbers: scores!) { //強(qiáng)制解包,上段代碼已經(jīng)保證了其安全
    print("The max score is \(result.max)")
    print("The min score is \(result.min)")
}

e.g.3: 調(diào)用時(shí)隱藏變量名

// 下劃線代表忽略
func mutiply(_ num1: Int, _ num2: Int) -> Int {
    return num1 * num2
}
mutiply(2, 3)

e.g.4: 默認(rèn)參數(shù)和可變參數(shù)

//變長(zhǎng)型函數(shù)參數(shù)
print("Hello",1, 2, 3, separator: "|", terminator: "...") // Hello|1|2|3...
//例子
func mean(_ numbers: Double ...) -> Double {
    var sum: Double = 0
    
    for number in numbers {
        sum += number
    }
    
    return sum / Double(numbers.count)
}

mean(numbers: 3)
mean(numbers: 2, 4)
mean(numbers: 3, 4, 8)

e.g.5: 函數(shù)可以作為參數(shù)使用

//1. 當(dāng)函數(shù)有兩個(gè)參數(shù),同時(shí)有返回值時(shí)
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

//let anotherAdd = add
let anotherAdd: (Int, Int) -> Int = add   //將函數(shù)當(dāng)作變量使用


//2. 當(dāng)函數(shù)只有一個(gè)參數(shù),返回值是空時(shí)
func sayHello(name: String) {
    print("Hello, \(name)")
}

let anotherSayHello: (String) -> () = sayHello
//let anotherSayHello: (String) -> Void = sayHello

//3. 當(dāng)函數(shù)即沒有參數(shù)也沒有返回時(shí)值
func sayHello(){
    print("Hello")
}

let anotherSayHello1: () -> () = sayHello
let anotherSayHello2: () -> Void = sayHello


//算法1. 默認(rèn)從小到大排序
var arr: [Int] = []
for _ in 0..<100 {
    arr.append(Int(arc4random() % 1000))
}
arr.sort() //改變arr本身
arr.sorted() //不改變arr本身

//算法2. 按從大到小排序
func biggerNumberFirst(_ a: Int, _ b: Int) -> Bool {
    return a > b
}
arr.sort(by: biggerNumberFirst)

//算法3. 首位是1..2..3..4的排序
func cmpByNumberString(_ a: Int, _ b: Int) -> Bool {
    return String(a) < String(b)
}
arr.sort(by: cmpByNumberString)
//print(arr)

//算法4. 誰(shuí)離500更近
func near500(_ a: Int, _ b: Int) -> Bool {
    return abs(500-a) < abs(500-b) //abs():取絕對(duì)值
}
arr.sort(by: near500)

//自己定義排序的規(guī)則,然后統(tǒng)一傳到sort()函數(shù)里,實(shí)現(xiàn)任何想要的排序方法

e.g.6:高階函數(shù)初探

func changeScores1(scores: inout [Int]){

    for (index, score) in scores.enumerated() {
        scores[index] = Int(sqrt(Double(score)) * 10)
    }
}

func changeScores2(scores: inout [Int]) {

    for (index, score) in scores.enumerated() {
        scores[index] = Int(Double(score) / 300 * 100)
    }
}

var scores1 = [36, 61, 78, 89, 91]
changeScores1(scores: &scores1)

var scores2 = [188, 240, 220, 260, 160]
changeScores2(scores: &scores2)

//高階函數(shù),函數(shù)式編程初探

//1. 初階抽象
//建立通用的函數(shù)模版(把函數(shù)當(dāng)參數(shù)傳入)
func changeScores(scores: inout [Int], changeMethod: (Int) -> Int) {

    for (index, score) in scores.enumerated() {
        scores[index] = changeMethod(score)
    }
}

//實(shí)現(xiàn)具體改變的方式
func changeMethod1(score: Int) -> Int {
    return Int(sqrt(Double(score)) * 10)
}

func changeMethod2(score: Int) -> Int {
    return Int(Double(score) / 300 * 100)
}

//調(diào)用時(shí)將函數(shù)名作為參數(shù)傳入
var scores1 = [36, 61, 78, 89, 91]
//changeScores(scores: &scores1, changeMethod: changeMethod1)

var scores2 = [188, 240, 220, 260, 160]
//changeScores(scores: &scores2, changeMethod: changeMethod2)



//2. 三大著名函數(shù), 高階抽象

var scores = [65, 91, 45, 59, 87]

//map():遍歷,把調(diào)用的數(shù)組根據(jù)參數(shù)(函數(shù))變化成另一個(gè)新的數(shù)組,返回新的數(shù)組
scores.map(changeMethod1) //更高一層的抽象

func isPassOrFail(score: Int) -> String {
    return score > 60 ? "Pass" : "Fail"
}
scores.map(isPassOrFail) // ["Pass", "Pass", "Fail", ...


//filter(): 遍歷,根據(jù)參數(shù)(函數(shù))規(guī)則來過濾,返回過濾后的新數(shù)組
func fail(score: Int) -> Bool {
    return score < 60
}
//filter接收的函數(shù)參數(shù)必須返回的是Bool型
scores.filter(fail) // [45, 59]


//reduce(): 遍歷,最終聚合成一個(gè)值,此處為計(jì)算數(shù)組的和

func add(num1: Int, num2: Int) -> Int {
    return num1 + num2
}
scores.reduce(0, add)
scores.reduce(0, +) //用法相同

func concatenate(str: String, int: Int) -> String{
    return str + String(int) + " | "
}
scores.reduce("+", concatenate) // +65 | 91 | 45 | 59 | 8...

e.g.7:函數(shù)的嵌套和作為返回值

func tier1MailFeeByWeight(weight: Int) -> Int {
   return 1 * weight
}

func tier2MailFeeByWeight(weight: Int) -> Int {
   return 3 * weight
}


func feeByUnitPrice(price: Int, weight: Int) -> Int {
   
   //返回值是函數(shù)
   func chooseMailFeeCalculationByWeight(_ weight: Int) -> (Int) -> (Int) {
       return weight >= 10 ? tier2MailFeeByWeight : tier1MailFeeByWeight
   }

   let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight) //變量代表一個(gè)函數(shù),因此可以給他賦值
   return mailFeeByWeight(weight) + price * weight 
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容