Swift学习笔记三:函数

三、函数

1.函数func以及函数的参数和返回值

函数:是执行指定任务的代码块,给定一个函数名称标识,当执行其任务时,就可以用这个标识进行调用。

1.1 定义无参函数

func ssyHelloSwift()

{

    //使用func关键词定义一个函数,并制定函数名为sayHelloSwift,尾部小括号用来设置参数,大括号之内用来放置执行某项任务的代码块

    print("hello, swift")

}

ssyHelloSwift()


1.2 定义带一个参数的函数

func sayHello(to: String)

{

    print("hello,\(to)!")

}

sayHello(to: "xcode")


1.3 定义无参、但拥有一个返回值的函数

func saySomething() -> String

{

    return "Hello, coolKatang"

}

print(saySomething())


1.4 定义一个参数、一个返回值的函数

func sayGreeting(to: String) -> String

{

    return "hi,\(to)"

}

print(sayGreeting(to: "dddd"))



2.函数的外部参数名

func getDistance(startPoint point1:CGPoint, endPoint point2:CGPoint) -> CGFloat

{

    let xDistance = point2.x - point1.x

    let yDistance = point2.y - point1.y

    return sqrt(xDistance * xDistance + yDistance * yDistance)

}


let p1 = CGPoint(x: 0, y: 0)

let p2 = CGPoint(x: 100, y: 100)

getDistance(startPoint: p1, endPoint: p2)


func getDistance2(startPoint:CGPoint, endPoint:CGPoint) -> CGFloat

{

    let xDistance = endPoint.x - startPoint.x

    let yDistance = endPoint.y - startPoint.y

    return sqrt(xDistance * xDistance + yDistance * yDistance)

}


getDistance(startPoint: p1, endPoint: p2)



3.创建拥有任意数量参数的函数

//可变参数的用法:一个作为可变参数的参数,可以接受0个或多个指定类型的值

//创建可变的参数时,需要在参数类型名称的后面加上点字符(...),这样参数将作为一个双精度类型的浮点数组存在

func getAverage(number: Double...) -> Double

{

    if number.count == 0 {

        return 0.0

    }

    var total: Double = 0

    for numbers in number {

        total += numbers

    }

    return total / Double(number.count)

}

print(getAverage())

getAverage(number: 1, 2, 3, 4)



4.函数的输入输出inout参数解析

//输入输出函数的使用:如果需要一个函数可以修改参数的值,并且想让修改可以保持在函数调用之后,那么就可以使用输入输出参数

//通过在参数类型的前方添加inout关键词,声明一个输入-输出类型的参数

func swap(a: inout Double, b: inout Double)

{

    let tempA = a

    a = b

    b = tempA

}

//定义一个浮点类型的变量,参数列表中只可以传递变量作为一个输入输出参数,而不能传递一个常数或常值作为参数,因为常量和数值不能修改

var myScore = 6.5

var youScore = 9.0

//调用函数,并在变量名称之前放置一个连字符(&),表示他可以作为输入输出参数进行修改

swap(&myScore, &youScore)

myScore

youScore



5.给函数的参数设置默认的取值

//将使用默认值的参数,放在参数列表的末尾,这可以确保所有调用函数的非默认参数使用正常的顺序

func getDistance3(startPoint: CGPoint, endPoint: CGPoint = CGPoint(x: 0, y: 0)) -> CGFloat

{

    let xDistance = endPoint.x - startPoint.x

    let yDistance = endPoint.y - startPoint.y

    return sqrt(xDistance * xDistance + yDistance * yDistance)

}

let p3 = CGPoint(x: 0, y: 0)

let p4 = CGPoint(x: 100, y: 100)

getDistance3(startPoint: p4, endPoint: p3)

getDistance3(startPoint: p4)



6.使用函数作为另一个函数的参数

func getTotal(num1: Int, num2: Int) -> Int

{

    return num1 + num2

}


func getBigger(num1: Int, num2: Int) -> Int

{

    return num1 > num2 ? num1 : num2

}


func getResult(function:(Int, Int) -> Int, a: Int, b: Int)

{

    print("result is: \(function(a,b))")

}


getResult(function: getTotal, a: 2, b: 3)

getResult(function: getBigger, a: 4, b: 5)



7.函数类型的解析

func getTotals(number1: Int, number2: Int) -> Int

{

    return number1 + number2

}

getTotals(number1: 1, number2: 1)


let newFunction:(Int, Int) ->Int = getTotals

newFunction(1, 2)


let anotherFunction = getTotals

anotherFunction(3, 4)


func printfHHHH()

{

    print("hhhhh,hhhh")

}


let antherPirint:()->() = printfHHHH

antherPirint()



8.使用函数类型作为函数的返回类型

func stepForward(input: Int) -> Int

{

    return input + 1

}


func stepBackward(input: Int) -> Int

{

    return input - 1

}


func chooseStepFunction(isBack: Bool) -> (Int) ->Int

{

    return isBack ? stepBackward : stepForward

}

var cuurenValue = 4

let move = chooseStepFunction(isBack: cuurenValue > 0)

move(8)



9.函数可以拥有多个返回值

//我们可以使用一个元组类型,作为函数的返回类型,从而返回一个有多个值组成的元组,作为函数的返回值

func caculate(string: String) -> (vawels: Int, consonants: Int, other: Int)

{

    var vawels = 0

    var consonants = 0

    var other = 0

    for character in string.characters {

        switch String(character).lowercased() {

        case "a", "e", "i", "o", "u":

            vawels += 1

        case "b", "d", "d", "f", "g", "h", "j", "k", "l", "s":

            consonants += 1

        default:

            other += 1

        }

    }

    return(vawels, consonants, other)

}


caculate(string: "hello,wordls")



10.藏在函数内部的函数

func chooseFunction(isBack: Bool) -> (Int) ->Int

{

    func stepForward1(input: Int) -> Int

    {

        return input + 1

    }

    func stepBack1(input: Int) -> Int

    {

        return input - 1

    }

    return isBack ? stepBack1 : stepForward1

}

var cuurenV = -1

let move1 = chooseFunction(isBack: cuurenV > 0)

move1(8)



11.递归函数的使用解析

func recursion(n: Int) -> Int

{

    if n <= 1 {

        return 1

    }

    else{

        return recursion(n: n-1) + recursion(n: n-2)

    }

}


recursion(n: 8)




12.Swift那些非常实用的内部函数

abs(-2) //获取参数绝对值

assert(true) // 断言函数:当其参数为真时,函数被正常执行;为假时,抛出异常。主要用于程序调试和异常处理

max(2, 1) //获得两个参数中的最大值

max(1, 2, 3, 4, 5)

min(2, 1) //获得两个参数中的最小值

min(1, 2, 3, 4, 5)

print("hello,","world")

debugPrint("hello,","world")

print("i", "have", "6", "stars", separator:"...")

print("i", "have", "6", "stars", separator: "...", terminator: "?")


let zerose = repeatElement("star", count: 5) //定义一个具有5个重复字符串的数组


var aa = "ssss"

var bb = "grgas"

swap(&aa, &bb) //交换两个变量的值

aa

bb


type(of: "aa") //获得参数的数据类型

type(of: 1)

type(of: 1.5)


for i in (1...10).filter({$0 % 3 == 0}) { //过滤函数:对需要循环的数组进行过滤,在此只对3的倍数进行循环遍历

    print(i)

}


for i in (1...4).map({$0 * 3}) //映射函数:对需要循环的数组进行映射,在此使数组中的元素都乘以3

{

    print(i)

}


let resurlts = (1...4).reduce(0, {$0 + $1}) //将序列中的值进行统一处理,在此例中,会将初始值0,分别与数组中的每个元素进行累加,并返回最终的结果。大括号表示一个闭包

print(resurlts)


let resurlts1 = (1...4).reduce(0, +) //闭包语句可以省略为一个符号

print(resurlts1)


let resurlts2 = (1...4).reduce(0, *)

print(resurlts2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值