美文网首页
Swift 2 学习笔记 8.函数

Swift 2 学习笔记 8.函数

作者: Maserati丶 | 来源:发表于2018-11-21 20:28 被阅读0次

课程来自慕课网liuyubobobo老师


函数
  • 函数基础
func sayHello(name: String?) -> String {
    return "Hello " + ( name ?? "Guest" )
}

var nickname: String? = nil
sayHello(name: nickname)
  • 使用元组返回多个值
func findMaxAndMin( numbers: [Int] ) -> ( max: Int, min: Int )? {
    if numbers.isEmpty {
        return nil
    }
    var minValue = numbers[0]
    var maxValue = numbers[0]
    for number in numbers {
        minValue = minValue < number ? minValue : number
        maxValue = maxValue > number ? maxValue : number
    }
    return (maxValue, minValue)
}

var scores: [Int]? = [21,123,53,122,33,252]
scores = scores ?? nil
if let result = findMaxAndMin(numbers: scores!) {
    print(result.max)
    print(result.min)
}
  • 函数的命名
func sayHello(to name: String, with greeting: String) -> String {
    return "\(greeting),\(name)"
}

sayHello(to: "imooc", with: "Hello")

func mutiple(_ num1: Int,_ num2: Int) -> Int {
    return num1 * num2
}

mutiple(4, 2)
  • 默认参数值
func sayHello(to name: String = "Playground", with greeting: String = "Hello") -> String {
    return "\(greeting),\(name)"
}

sayHello(to: "imooc", with: "Hi")  // Hi,imooc
sayHello(to: "bobobo")  // Hello,bobobo
sayHello()// Hello,Playground
  • 可变参数
func mean(_ numbers:Double ...) -> Double {
    var sum:Double = 0
    // 将变长参数当做一个数组看待
    for number in numbers {
        sum += number
    }
    return sum/Double(numbers.count)
}

mean(2)  // 2
mean(2,3)  // 2.5
mean(2,3,41,5,1,23,4,52)  // 16.375


func sayHello(to names: String ... , with greeting: String = "Hello") {
    for name in names {
        print("\(greeting),\(name)")
    }
}

sayHello(to: "A","B","C", with: "Hi")
  • 常量参数、变量参数和inout参数 -> Swift3
// 变量参数不再使用
// inout关键字写在参数后面
// 交换两个整型
func swapTwoInts(_ a: inout Int , _ b : inout Int) {
    (a,b) = (b,a)
}
var numA: Int = 3
var numB: Int = 4
swapTwoInts(&numA, &numB)
numA  // 4
numB  // 3

// 将一个整型数组每一个元素都初始化成0
func initArray(arr: inout [Int], by value:Int ) {
    for i in 0..<arr.count {
        arr[i] = value
    }
}
var arr = [1,2,3]
initArray(arr: &arr, by: 0)
arr  // [0,0,0]
  • 函数类型
// 产生一个随机数组
var arr: [Int] = []
for _ in 0..<100 {
    arr.append(Int(arc4random()%1000))
}
// 按从大到小排序
func biggerNumberFirst (a: Int , b: Int) -> Bool {
    return a > b
}
arr.sort(by: biggerNumberFirst)
// 按最接近500排序
func near500 (a: Int, b: Int) -> Bool {
    return abs(a-500) < abs(b-500) ? true : false
}
arr.sort(by: near500)
  • 函数式编程初步
func changeScores ( scores: inout [Int], by changeScore:(Int) -> Int ) {
    for (index,score) in scores.enumerated() {
        scores[index] = changeScore(score)
    }
}

func changeScore1 (score: Int) -> Int {
    return Int(sqrt(Double(score))*10)
}

func changeScore2 (score: Int) -> Int {
    return Int(Double(score)/150.0*100.0)
}

var scores1 = [67,72,45,96,80]
changeScores(scores: &scores1, by: changeScore1)

var scores2 = [123,78,96,102,88]
changeScores(scores: &scores2, by: changeScore2)


//map
var scores = [67,72,45,96,80]
scores.map(changeScore1)  // [81, 84, 67, 97, 89]
scores  // [67,72,45,96,80]

//filter
func fail(score: Int) -> Bool {
    return score < 60
}
scores.filter(fail)  // [45]
scores  // [67,72,45,96,80]

//reduce
func add(num1: Int, num2: Int ) -> Int {
    return num1 + num2
}
scores.reduce(0, add)  // 360
scores.reduce(0, +)  // 360
  • 返回函数类型和函数嵌套
// 两种邮费计算方法
func tier1MailFee(by weight: Int) -> Int {
    return 1 * weight
}

func tier2MailFee(by weight: Int) -> Int {
    return 3 * weight
}
// 计算商品总花费(邮费+商品价格)
func fee(price: Int, weight: Int) -> Int {
    // 嵌套选择邮费计算方法的函数
    func chooseMailFeeCalculation(by weight: Int) -> (Int) -> Int {
        return weight <= 10 ? tier1MailFee : tier2MailFee
    }
    
    let mailFeeByWeight = chooseMailFeeCalculation(by: weight)
    return mailFeeByWeight(weight) + price
}

fee(price: 100, weight: 10)  // 110
fee(price: 100, weight: 20)  // 160

相关文章

  • Swift 2 学习笔记 8.函数

    课程来自慕课网liuyubobobo老师 函数 函数基础 使用元组返回多个值 函数的命名 默认参数值 可变参数 常...

  • swift学习笔记②

    Swift学习笔记 - 文集 语法篇 一、函数 函数定义 Swift 定义函数使用关键字 func,functio...

  • swift学习笔记 函数

    本文章是本人学习 swift 时的笔记,略简单 1、函数的定义与调用: 2、无参数函数 3、无返回值函数 虽说是无...

  • Swift学习笔记

    swift学习笔记01: “一等公民“ func & closure 先来几个函数: 在swift中,我们可以这样...

  • Swift学习笔记①

    Swift学习笔记①Swift学习笔记①

  • swift学习笔记 ⑥ —— 闭包

    Swift学习笔记 - 文集 闭包,就是能够读取其他函数内部变量的函数。Swift 中的闭包与 C 和 OC 中的...

  • Swift学习笔记-函数

    最简单的函数 带参数的函数 外部参数 swift中参数名可以填两个,前者是外部参数名(调用者使用),后者是内部参数...

  • Swift学习笔记-函数

    (一)函数 1.如果函数的传入参数不同时,函数名可以是一样的(但是传入参数一样,返回值不一样的时候不行?或许某种方...

  • Swift 学习笔记(一)

    swift学习笔记第一篇,主要常量,变量,数据类型,条件判断,循环, 函数等基础知识的汇总 大纲汇总 Swift ...

  • swift学习笔记2——函数、闭包

    之前学习swift时的个人笔记,根据github:the-swift-programming-language-i...

网友评论

      本文标题:Swift 2 学习笔记 8.函数

      本文链接:https://www.haomeiwen.com/subject/qyrhqqtx.html