Swift入门(二)

前端之家收集整理的这篇文章主要介绍了Swift入门(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

函数

函数的定义、参数、返回值

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

可以省略参数和返回值

func sayGoodbye(personName: String) {
    println("Goodbye,\(personName)!")
}

也可以包含多个参数和多个返回值

func count(string1: String,string2: String) -> (vowels: Int,consonants: Int,others: Int) {
    var vowels = 0,consonants = 0,others = 0
    for character in string1 {
        switch String(character).lowercaseString {
        case "a","e","i","o","u":
            ++vowels
        case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
            ++consonants
        default:
            ++others
        }
    }
    return (vowels,consonants,others)
}

多重返回值返回的是一个元祖,没有返回值时其实返回的是Void,一个空的元祖

参数名

参数名一般只能函数内部使用,但为了使语言表达更清晰,可以定义外部参数名,使用这些外部参数名使代码更易阅读

func join(string s1: String,toString s2: String,withJoiner joiner: String) -> String {
    return s1 + joiner + s2
}

join(string: "hello",toString: "world",withJoiner: ",")

外部名可以与内部名保持一致

func containsCharacter(#string: String,#characterToFind: Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

let containsAVee = containsCharacter(string: "aardvark",characterToFind: "v")

函数参数可以提供默认值

func join(string s1: String,withJoiner joiner: String = " ") -> String {
    return s1 + joiner + s2
}

join(string: "hello",toString:"world")
// returns "hello world"
join(string: "hello",withJoiner: "-")
// returns "hello-world"

对提供了默认值的参数,参数名自动表示为内部名和外部名
输入输出参数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)

函数类型

函数类型由参数类型和返回值类型共同决定,类似c语言的函数指针

func addTwoInts(a: Int,b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(a: Int,b: Int) -> Int {
    return a * b
}
var mathFunction: (Int,Int) -> Int = addTwoInts
println("Result: \(mathFunction(2,3))")

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

函数类型与其他类型一样,可以做参数,也可以做返回值

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)

函数可以嵌套

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

闭包

闭包特性应用在嵌套函数和闭包表达式中,是一种函数式编程特性

闭包表达式

一般形式如下

{ (parameters) -> returnType in
    statements
}

例如

reversed = sorted(names,{ (s1: String,s2: String) -> Bool in return s1 > s2 }) // 闭包可以类型推断,所以可以简化为 reversed = sorted(names,{ s1,s2 in return s1 > s2 } ) // 单行表达式可以省略返回的return reversed = sorted(names,s2 in s1 > s2 } ) // 还可以缩写参数 reversed = sorted(names,{ $0 > $1 } )

如果闭包函数很长,为了增强可读性,可以讲闭包函数放到()外边紧跟函数调用

func someFunctionThatTakesAClosure(closure: () -> ()) { // 函数体部分 } // 以下是使用尾随闭包进行函数调用 someFunctionThatTakesAClosure() { // 闭包主体部分 }

捕获值

闭包可以在其定义的上下文中捕获常量或变量。 即使定义这些常量和变量的原域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值。

func makeIncrementor(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementor() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementor
}

let incrementByTen = makeIncrementor(forIncrement: 10)

incrementByTen()
// 返回的值为10
incrementByTen()
// 返回的值为20
incrementByTen()
// 返回的值为30

猜你在找的Swift相关文章