美文网首页
Swift 函数

Swift 函数

作者: 点滴86 | 来源:发表于2016-08-05 18:40 被阅读10次

函数的定义与调用

import UIKit

// 函数的定义与调用
func greet(person : String) -> String {
    let greeting = "Hello, " + person + "!"
    
    return greeting
}

print(greet("Kobe"))

console log 如下


函数的定义与调用.png

无参数的函数

// 无参数的函数
func sayHelloWorld() -> String {
    return "hello, world"
}

print(sayHelloWorld())

console log 如下


无参数的函数.png

多个参数的函数

// 多个参数的函数
func greet(person: String, alreadyGreeted: Bool) -> String {
    var greeting = ""
    if alreadyGreeted {
        greeting = "Hello again, " + person + "!"
    } else {
        greeting = "Hello, " + person + "!"
    }
    
    return greeting
}

print(greet("Kobe", alreadyGreeted: true))

console log 如下


多个参数的函数.png

没有返回值的函数

// 没有返回值的函数
func greetNoReturn(person: String) {
    print("Hello, \(person)!")
}

greetNoReturn("Kobe")

console log 如下


没有返回值的函数.png

多个返回值的函数

// 多个返回值的函数
func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for index in array {
        if index < currentMin {
            currentMin = index
        }
        
        if index > currentMax {
            currentMax = index
        }
    }
    
    return (currentMin, currentMax)
}


let bounds = minMax([1, 2, 3, 4, 5, 6])
print("min is \(bounds.min) and max is \(bounds.max)")

console log 如下


多个返回值的函数.png

返回可选元组

// 返回可选元组
func minMaxAgain(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty {
        return nil
    }
    var currentMin = array[0]
    var currentMax = array[0]
    for index in array {
        if index < currentMin {
            currentMin = index
        }
        
        if index > currentMax {
            currentMax = index
        }
    }
    
    return (currentMin, currentMax)
}

if let tempBounds = minMaxAgain([1, 2, 3, 4, 100, -520, 520]) {
    print("min is \(tempBounds.min) and max is \(tempBounds.max)")
}

console log 如下


返回可选元组.png

外部参数名

// 外部参数名
func someFunction(name person: String, from hometown: String) -> String {
    
    return "Hello \(person)! Glad you could visit from \(hometown)."
}

print(someFunction(name: "Kobe", from: "Los Angeles"))

console log 如下


外部参数名.png

参数默认值

// 参数默认值
func defaultParameterFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 520) {
    print("parameter without default value is \(parameterWithoutDefault) and parameter with default value is \(parameterWithDefault)")
}

defaultParameterFunction(12)

defaultParameterFunction(12, parameterWithDefault: 10)

console log 如下


参数默认值.png

参数个数可变

// 参数个数可变
func arithmeticMean(numbers: Double...) -> Double {
    var total : Double = 0
    for number in numbers {
        total += number
    }
    
    return total / Double(numbers.count)
}

print("1, 2, 3, 4, 5 的平均值是 \(arithmeticMean(1, 2, 3, 4, 5))")

print("1, 2, 3 的平均值是 \(arithmeticMean(1, 2, 3))")

console log 如下


参数个数可变.png

In-Out 参数

// In-Out 参数
func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
print("before swap : someInt value is \(someInt) and anotherInt value is \(anotherInt)")
swapTwoInts(&someInt, b: &anotherInt)
print("after swap : someInt value is \(someInt) and anotherInt value is \(anotherInt)")

console log 如下


In-Out 参数.png

函数类型

// 函数类型

// (Int, Int) -> Int
func addTwoInts(a: Int, b: Int) -> Int {
    return a + b
}

func multiplyTwoInts(a: Int, b: Int) -> Int {
    return a * b
}

// () -> void
func printHelloWorld(){
    print("Hello, world")
}

var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")

mathFunction = multiplyTwoInts
print("Result: \(mathFunction(2, 3))")

printHelloWorld()

console log 如下


函数类型.png

函数类型作为函数参数

// 函数类型作为函数参数
func printMathResult( mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
    print("Result: \(mathFunction(a, b))")
}

printMathResult(addTwoInts, a: 8, b: 5)

console log 如下

函数类型作为函数参数.png

函数类型作为返回类型

// 函数类型作为返回类型
func stepForward(input: Int) -> Int {
    return input + 1
}

func backForward(input: Int) -> Int {
    return input - 1
}

func chooseStepFunction(backword: Bool) -> (Int) -> Int {
    if backword {
        return backForward
    } else {
        return stepForward
    }
}

var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
print("Counting to zero:")
while currentValue != 0 {
    print("\(currentValue)...")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")

console log 如下


函数类型作为返回类型.png

嵌套函数

// 嵌套函数
func anotherChooseStepFunction(backword: Bool) -> (Int) -> Int {
    func anotherStepForward(input: Int) -> Int {
        return input + 1
    }
    
    func anotherBackForward(input: Int) -> Int {
        return input - 1
    }
    
    if backword {
        return anotherBackForward
    } else {
        return anotherStepForward
    }
}

var anotherCurrentValue = -4
let anotherMoveNearerToZero = chooseStepFunction(anotherCurrentValue > 0)
print("Counting to zero:")
while anotherCurrentValue != 0 {
    print("\(anotherCurrentValue)...")
    anotherCurrentValue = anotherMoveNearerToZero(anotherCurrentValue)
}
print("zero!")

console log 如下


嵌套函数.png

相关文章

  • Swift学习笔记(二)

    Swift函数 Swift函数包含参数类型和返回值类型 函数定义 Swift使用关键字func定义函数。 函数定义...

  • Swift中的标准函数

    Swift中的标准函数 Swift中的标准函数

  • Swift の 函数式编程

    Swift の 函数式编程 Swift の 函数式编程

  • 10.函数(function)

    函数 kotlin_函数 swift_函数

  • swift 函数

    Swift 函数 函数声明: 告诉编译器函数的名字,返回类型及参数。 函数定义: 提供了函数的实体。Swift 函...

  • swift学习笔记②

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

  • #6 函数

    swift functions - 极客学院 swift的函数和JS的函数基本类似,有几点不同的是: swift中...

  • iOS知识点-9.Swift 是面向对象还是函数式的编程语言?

    Swift Basics Swift 是面向对象还是函数式的编程语言? Swift既是面向对象的,又是函数式的编程...

  • Swift高阶函数解析

    一、锲子 最近在学习Swift过程中发现,Swift有不少高阶函数,这些函数为Swift支持函数式编程范式提供了强...

  • swift 临时

    //// ViewController.swift// Swift01_函数//// Created by ...

网友评论

      本文标题:Swift 函数

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