美文网首页
Swift 基础知识二:函数

Swift 基础知识二:函数

作者: 对歌当酒 | 来源:发表于2016-03-09 19:48 被阅读41次

使用 func 来声明一个函数,使用名字和参数来调用函数,使用 -> 来指定函数返回值的类型。例如:

func greet(name: String, day: String) -> String 
{
    return "Hello \(name), today is \(day)."
}

//调用函数(注意第一个参数不含参数名)
greet("Bob", day: "Tuesday")

无参数的函数:

// 后面的 Void 可用 () 替代或省略不写
func sayWelcome() -> Void
{
    print("Nice to meet you!")
}
  • 使用元组来让一个函数返回多个值。
    该元组的元素可以用名称或数字来表示。例如:
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) 
{
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])

print(statistics.sum)
print(statistics.2) //这两种方式都可以
  • 函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式:
func sumOf(numbers: Int...) -> Int 
{
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)
  • 函数可以嵌套,被嵌套的函数可以访问外侧函数的变量。可以使用嵌套函数来重构一个太长或者太复杂的函数。例如:
func returnFifteen() -> Int 
{
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()
  • 函数可以作为另一个函数的返回值。

The next example defines two simple functions called stepForward(_:) and stepBackward(_:). The stepForward(_:) function returns a value one more than its input value, and the stepBackward(_:) function returns a value one less than its input value. Both functions have a type of (Int) -> Int:

func stepForward(input: Int) -> Int {
    return input + 1
}
func stepBackward(input: Int) -> Int {
    return input - 1
}

Here’s a function called chooseStepFunction(_:), whose return type is “a function of type (Int) -> Int”. The chooseStepFunction(_:) function returns the stepForward(_:) function or the stepBackward(_:) function based on a Boolean parameter called backwards:

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    return backwards ? stepBackward : stepForward
}

chooseStepFunction是一个返回函数的函数(其类型准确说来是:接受一个 Bool 型参数,并返回一个函数,该函数接受一个 Int 型变量并返回一个 Int 值),如果参数 backwards 为真就返回 stepBackward,否则就返回 stepForward

The Swift Programming Language (Swift 2.2): Founctions

  • 函数也可以当做参数传入另一个函数。例如:
func addTwoInts(a: Int, _ b: Int) -> Int {
    return a + b
}

func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Prints "Result: 8"

本例定义了一个名为 printMathResult(_:_:_:) 的函数,该函数有三个参数。第一个参数名为 mathFunction, 类型为 (Int, Int) -> Int.
PS: 参数 a, b 前的下划线 _ 表示调用该函数的时候不写参数名。

《The Swift Programming Language 中文版》

相关文章

  • Swift5.0 - day1-基础介绍与基本运算

    一、基础知识 1.1、Swift 不用编写main函数(本质上swift是有main函数的),Swift将全局范围...

  • Swift 基础知识二:函数

    使用 func 来声明一个函数,使用名字和参数来调用函数,使用 -> 来指定函数返回值的类型。例如: 无参数的函数...

  • Swift 学习笔记(一)

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

  • 托XX福写个Swift闭包教程

    闭包基础知识 Swift闭包和OC的block类似不过还是有点区别 OC的block是一个匿名函数 Swift 中...

  • Swift常用基础知识(二)

    Swift常用基础知识(一)[https://www.jianshu.com/p/d6e214ce7f02] 函数...

  • Swift 烧脑体操

    Swift 烧脑体操(一) - Optional 的嵌套 Swift 烧脑体操(二) - 函数的参数 Swift ...

  • swift函数基础知识

    1、函数声明和调用 通用函数声明格式:func 函数名称(形参名:形参类型,形参名:形参类型,···)->返回值类...

  • swift学习之路

    swift3.0.1官方文档下载链接 swift(一)简单值 swift(二)流程控制 swift(三)函数和闭包...

  • swift学习资料整理

    基础知识篇 Swift Programming Language Using Swift with Cocoa a...

  • Swift 基本语法(函数, 闭包)

    前言 接上篇, 这篇聊一下 Swift中的 函数, 闭包 一 函数 二 闭包 Swift 基础 先介绍三篇, ...

网友评论

      本文标题:Swift 基础知识二:函数

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