Swift-函数

e.g.1

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

e.g.2: 使用元组返回多个值

func findMaxAndMin(numbers: [Int]) -> (max: Int, min: Int)? {
    
//    当数组为空的时候,返回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直接赋一个空数组

if let result = findMaxAndMin(numbers: scores!) { //强制解包,上段代码已经保证了其安全
    print("The max score is \(result.max)")
    print("The min score is \(result.min)")
}

e.g.3: 调用时隐藏变量名

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

e.g.4: 默认参数和可变参数

//变长型函数参数
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: 函数可以作为参数使用

//1. 当函数有两个参数,同时有返回值时
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

//let anotherAdd = add
let anotherAdd: (Int, Int) -> Int = add   //将函数当作变量使用


//2. 当函数只有一个参数,返回值是空时
func sayHello(name: String) {
    print("Hello, \(name)")
}

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

//3. 当函数即没有参数也没有返回时值
func sayHello(){
    print("Hello")
}

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


//算法1. 默认从小到大排序
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. 谁离500更近
func near500(_ a: Int, _ b: Int) -> Bool {
    return abs(500-a) < abs(500-b) //abs():取绝对值
}
arr.sort(by: near500)

//自己定义排序的规则,然后统一传到sort()函数里,实现任何想要的排序方法

e.g.6:高阶函数初探

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)

//高阶函数,函数式编程初探

//1. 初阶抽象
//建立通用的函数模版(把函数当参数传入)
func changeScores(scores: inout [Int], changeMethod: (Int) -> Int) {

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

//实现具体改变的方式
func changeMethod1(score: Int) -> Int {
    return Int(sqrt(Double(score)) * 10)
}

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

//调用时将函数名作为参数传入
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. 三大著名函数, 高阶抽象

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

//map():遍历,把调用的数组根据参数(函数)变化成另一个新的数组,返回新的数组
scores.map(changeMethod1) //更高一层的抽象

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


//filter(): 遍历,根据参数(函数)规则来过滤,返回过滤后的新数组
func fail(score: Int) -> Bool {
    return score < 60
}
//filter接收的函数参数必须返回的是Bool型
scores.filter(fail) // [45, 59]


//reduce(): 遍历,最终聚合成一个值,此处为计算数组的和

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:函数的嵌套和作为返回值

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

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


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

   let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight) //变量代表一个函数,因此可以给他赋值
   return mailFeeByWeight(weight) + price * weight 
}

你可能感兴趣的:(Swift-函数)