美文网首页
swift-函数

swift-函数

作者: malgee | 来源:发表于2018-03-22 11:17 被阅读3次
函数也可以作为一个类型(引用类型)
func add (_ a: Int, _ b: Int) -> Int
{
    return a + b
}

let anotherAdd = add  // let anotherAdd: (Int, Int) -> Int = add 等同于, 这里的 add 函数作为一个类型
anotherAdd(2, 4)


`_` 表示忽略参数名  `= 99999, =1000` 表示默认值
func add(_ num1: Int = 99999, _ num2: Int = 1000) -> Int
{
    return num1 + num2
}

add(2, 3)

add(2)

// 这里调用 是因为有默认参数
add()


// 这里的 `and` 是外部参数名
func add(_ num1: Int = 99999, _ num2: Int = 1000,  and num3: Int) -> Int
{
    return num1 + num2 + num3
}

add(and: 3)

add(2, 3, and: 4)

变长的参数类型
一个函数最多只有一个变长的参数类型

func mean (_ numbers: Int ...) -> Int
{
    var sumValue = 0
    
    for num in numbers {
        
        sumValue += num
    }
    
    return sumValue
}

// 这里可以传入多个值
mean(2, 4, 6, 8, 10)

交换2个数的值
inout 代表传入地址, 加上这个关键字后可以改变出入的参数值

func swapValues (_ num1: inout Int, _ num2: inout Int)
{
    let temp: Int = num1

    num1 = num2

    num2 = temp
}

var X: Int = 100, Y: Int = 200

swapValues(&X, &Y)

X
Y

参数是函数


func calculate(scores: inout [Int] , changeValue: (Int) -> Int) {
    
    for (index, score) in scores.enumerated() {
        
        scores[index] = changeValue(score);
    }
    print(scores)
}

func changeValue(value: Int) -> Int {
    
    return value * 10
}

var score: [Int] = [1, 2, 3, 4, 5]

// 调用
calculate(scores: &score, changeValue: changeValue)

执行结果:[10, 20, 30, 40, 50]

高阶函数

高阶函数map、flatMap、filter、reduce

map: 可以对数组中的每一个元素做一次处理\
let scores = [40, 89, 100, 78, 97, 50]
func isPass (score: Int) -> Bool
{
    return score < 60
}

scores.map(isPass) // [true, false, false, false, false]
filer:过滤,可以对数组中的元素按照某种规则进行一次过滤

let scores = [40, 89, 100, 78, 97, 50]
func isPass (score: Int) -> Bool
{
    return score < 60
}

scores.filter(isPass)  // [40, 50]
reduce:计算,可以对数组的元素进行计算

func joint (string: String, num: Int) -> String
{
    return string + String(num) + ","
}

scores.reduce("", joint) // 40,89,100,78,97,50,

相关文章

  • 跟着洲洲哥一块学习Swift-函数

    本文首发地址 Swift-函数 当你定义一个函数时,你可以选择性地定义一个或多个名称,类型值作为函数的输入(称为形...

  • Swift-函数

    函数的定义与调用 无参数函数,有返回值(返回值类型String) 多参数函数,有返回值(返回值类型String) ...

  • Swift-函数

    1.函数的定义和调用 定义一个函数时,可以定义一个或多个有名字和类型的值,作为函数的输入,称为参数,也可以定义某种...

  • swift-函数

    函数也可以作为一个类型(引用类型) 变长的参数类型一个函数最多只有一个变长的参数类型 交换2个数的值inout 代...

  • Swift-函数

  • Swift-函数

    e.g.1 e.g.2: 使用元组返回多个值 e.g.3: 调用时隐藏变量名 e.g.4: 默认参数和可变参数 e...

  • Swift-函数

    重新阅读了Swift中文文档的函数章节,总结出以下文档中提到的13种函数,归纳如下:

  • Swift-函数

    定义和调用函数 在下面的例子中的函数叫做greet(person :),因为这是它的作用 - 它需要一个人的名字作...

  • Swift-函数

    定义函数 定义:func 函数名(参数1: 类型, 参数2: 类型, ...) -> 返回结果的类型 {执行语句}...

  • Swift-函数

    一、函数1、定义一个无参无返回值的函数并进行调用:func eat(){print(“eating”)}调用函数:...

网友评论

      本文标题:swift-函数

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