Swift (2), swift

Source: Internet
Author: User

Swift (2), swift
Function Definition, parameters, and return values

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

Parameters and return values can be omitted.

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

It can also contain multiple parameters and multiple return values.

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)}

Multiple return values return a ancestor. If no return value is returned, Void is returned, and an empty ancestor is returned.

Parameter Name

Generally, parameter names can only be used inside a function. To make the language clearer, you can define external parameter names. Use these external parameter names to make the code easier to read.

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

The external name can be consistent with the internal name.

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")

Function parameters can provide default values.

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

For parameters that provide the default value, the parameter name is automatically expressed as an internal name and an external name
Input and Output ParametersinoutThe parameter can be modified by the function body and reserved for external use.

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

You must add&

var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)
Function Type

Function types are jointly determined by parameter types and return value types. function pointers similar to C languages

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 = addTwoIntsprintln("Result: \(mathFunction(2, 3))")mathFunction = multiplyTwoIntsprintln("Result: \(mathFunction(2, 3))")

Function types, like other types, can be used as parameters or return values.

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 = 3let moveNearerToZero = chooseStepFunction(currentValue > 0)

Functions can be nested

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}
Closure

The closure feature is a functional programming feature applied to nested functions and closure expressions.

Closure expression

The general form is as follows:

{ (parameters) -> returnType in    statements}

For example

Reversed = sorted (names, {(s1: String, s2: String)-> Bool in return s1> s2}) // closure can be inferred by type, so it can be simplified to reversed = sorted (names, {s1, s2 in return s1> s2}) // a single row expression can omit the returned returnreversed = sorted (names, {s1, s2 in s1> s2}) // You can also abbreviated the parameter reversed = sorted (names, {$0> $1 })

If the closure function is very long, to enhance readability, you can put the closure function out of () to keep up with the function call,

Func someFunctionThatTakesAClosure (closure: ()-> () {// function body part} // The following is the use of the trailing closure for function call someFunctionThatTakesAClosure () {// closure body part}
Capture value

Closures can capture constants or variables in the context they define. Even if the original domain defining these constants and variables does not exist, the closure can still reference and modify these values in the closure function.

Func makeIncrementor (forIncrement amount: Int)-> ()-> Int {var runningTotal = 0 func incrementor () -> Int {runningTotal + = amount return runningTotal} return incrementor} let incrementByTen = makeIncrementor (forIncrement: 10) incrementByTen () // The returned value is 10 incrementByTen () // The returned value is 20 incrementByTen () // The returned value is 30.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.