Swift 学习记录(3)

<pre name="code" class="objc">import Foundation


/**
 *  1.函数的定义与与调用
 */

func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
}

print(sayHello("Anna"))
// prints "Hello, Anna!"


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


//------多参函数
func sayHello(personName: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return "Hello again " + personName;
    } else {
        return sayHello(personName)
    }
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"


//------无返回值函数
func sayGoodbye(personName: String) {
    print("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"


//------多重返回值函数,返回元组
func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}


let bounds = minMax([8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// prints "min is -6 and max is 109"




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

if let bounds = minMax1([8, -6, 2, 109, 3, 71]) {
    print("min is \(bounds.min) and max is \(bounds.max)")
}
// prints "min is -6 and max is 109"





/**
 *  2.函数参数名称
    函数参数都有一个外部参数名和一个局部参数名。外部参数名用于在函数调用时标注传递给函数的参数,局部参数名在函数的实现内部使用。
 */


func someFunction(firstParameterName: Int, secondParameterName: Int) {
    //一般情况下,第一个参数省略其外部参数名,第二个以及随后的参数使用其局部参数名作为外部参数名。
}
someFunction(1, secondParameterName: 2)



//-----指定外部参数名
func someFunction1(externalParameterName localParameterName: Int) {
    //如果你提供了外部参数名,那么函数在被调用时,必须使用外部参数名。
}

func sayHello1(to person: String, and anotherPerson: String) -> String {
    return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello1(to: "Bill", and: "Ted"))
// prints "Hello Bill and Ted!"



//-----忽略外部参数名,用_代替
func someFunction2(firstParameterName: Int, _ secondParameterName: Int) {
    // function body goes here
    // firstParameterName and secondParameterName refer to
    // the argument values for the first and second parameters
}
someFunction2(1, 2)

//-----默认参数值
func someFunction3(parameterWithDefault: Int = 12) {
    //将带有默认值的参数放在函数参数列表的最后。
}
someFunction3(6) // parameterWithDefault is 6
someFunction3() // parameterWithDefault is 12



//-----可变参数,通过在变量类型名后面加入(...)的方式来定义可变参数。
//一个函数最多只能有一个可变参数。如果函数有一个或多个带默认值的参数,而且还有一个可变参数,那么把可变参数放在参数表的最后。
func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers




/**
 *  3.输入输出参数
        函数参数默认是常量。试图在函数体中更改参数值将会导致编译错误。在参数加上inout
 */

func swapTwoInts(inout a: Int, inout _ b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"



/**
 *  4.函数类型
        每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。
 */


//这两个函数的类型是 (Int, Int) -> Int
func addTwoInts(a: Int, _ b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
    return a * b
}

//---------使用函数类型
//在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它

var mathFunction: (Int, Int) -> Int = addTwoInts

print("Result: \(mathFunction(2, 3))")
// prints "Result: 5"

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



//---------函数类型作为参数类型

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


//---------函数类型作为返回类型

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

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

var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function

print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// 3...
// 2...
// 1...
// zero!


/**
 *  5.嵌套函数
    之前见到的所有函数都叫全局函数,它们定义在全局域中。你也可以把函数定义在别的函数体中,称作嵌套函数。
 */


func chooseStepFunction5(backwards: Bool) -> (Int) -> Int {
    func stepForward5(input: Int) -> Int { return input + 1 }
    func stepBackward5(input: Int) -> Int { return input - 1 }
    return backwards ? stepBackward5 : stepForward5
}
var currentValue5 = -4
let moveNearerToZero5 = chooseStepFunction5(currentValue5 > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue5 != 0 {
    print("\(currentValue5)... ")
    currentValue5 = moveNearerToZero5(currentValue5)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值