Swift Functions
Swift functions are self-contained blocks of code that perform a specific task.\n\nSwift uses a unified syntax to express everything from simple C-style functions to complex Objective-C-style methods.\n\n* Function declaration: Tells the compiler the function's name, return type, and parameters.\n\n* Function definition: Provides the body of the function.\n\nSwift functions include parameter types and return types:\n\n* * *\n\n## Function Definition\n\nSwift uses the **func** keyword to define functions.\n\nWhen defining a function, you can specify one or more input parameters and a return type.\n\nEach function has a function name that describes its functionality. You call a function using its name and the corresponding parameter values of the appropriate types. The order in which parameters are passed must match the parameter list.\n\nThe order in which actual arguments are passed must match the formal parameter list. The return type of the function is defined after **->**.\n\n### Syntax\n\nfunc funcname(Parameters) -> returntype { Statement1 Statement2 β¦β¦ Statement N return parameters }\n### Example\n\nBelow we define a function named tutorial, with the formal parameter data type as String, and the return value also as String:\n\nimport Cocoa func tutorial(site: String) -> String { return (site)}print(tutorial(site: "example.com"))\nThe output of the above program execution is:\n\nexample.com\n\n* * *\n\n## Function Calling\n\nWe can call a function using its name and the corresponding parameter values of the appropriate types. The order in which parameters are passed must match the parameter list.\n\nBelow we define a function named tutorial, where the data type of the formal parameter site is String. When we call the function, the actual argument passed must also be of String type. After the actual argument is passed into the function body, it is directly returned, and the returned data type is String.\n\nimport Cocoa func tutorial(site: String) -> String { return (site)}print(tutorial(site: "example.com"))\nThe output of the above program execution is:\n\nexample.com\n\n* * *\n\n## Function Parameters\n\nA function can accept one or more parameters, which are enclosed in the function's parentheses and separated by commas.\n\nThe following example passes the site name name and site address site to the function tutorial:\n\nimport Cocoa func tutorial(name: String, site: String) -> String { return name + site }print(tutorial(name: "οΌ", site: "example.com"))print(tutorial(name: "GoogleοΌ", site: "www.google.com"))\nThe output of the above program execution is:\n\nοΌexample.com GoogleοΌwww.google.com\n\n* * *\n\n## Functions Without Parameters\n\nWe can create functions without parameters.\n\n### Syntax:\n\nfunc funcname() -> datatype { return datatype }\n### Example\n\nimport Cocoa func sitename() -> String { return ""}print(sitename())\nThe output of the above program execution is:\n\n* * *\n\n## Tuples as Function Return Values\n\nFunction return types can be strings, integers, floating-point numbers, etc.\n\nTuples are similar to arrays, but unlike arrays, the elements in a tuple can be of any type, and they use parentheses.\n\nYou can use a tuple type to return multiple values as a compound value from a function.\n\nIn the following example, a function named minMax(_:) is defined, which finds the minimum and maximum values in an Int array.\n\nimport Cocoa func minMax(array: ) -> (min: Int, max: Int) { var currentMin = array var currentMax = array for value in array[1..<array.count] { if value currentMax { currentMax = value } } return (currentMin, currentMax)}let bounds = minMax(array: [8, -6, 2, 109, 3, 71])print("Minimum value is (bounds.min) οΌMaximum value is (bounds.max)")\nThe minMax(_:) function returns a tuple containing two Int values, which are labeled min and max so that they can be accessed by name when querying the function's return value.\n\nThe output of the above program execution is:\n\nMinimum value is -6 οΌMaximum value is 109\nIf you are not sure whether the returned tuple will definitely not be nil, you can return an optional tuple type.\n\nYou can define an optional tuple by placing a question mark after the closing parenthesis of the tuple type, such as (Int, Int)? or (String, Int, Bool)?\n\n> Note\n> \n> An optional tuple type like `(Int, Int)?` is different from a tuple containing optional types like `(Int?, Int?)`. With an optional tuple type, the entire tuple is optional, not just each element value within the tuple.\n\nThe previous `minMax(_:)` function returned a tuple containing two `Int` values. However, the function does not perform any safety checks on the passed array. If the `array` parameter is an empty array, the `minMax(_:)` function as defined above will trigger a runtime error when trying to access `array`.\n\nTo safely handle this "empty array" issue, rewrite the `minMax(_:)` function to use an optional tuple return type, and return `nil` when the array is empty:\n\nimport Cocoa func minMax(array: ) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array var currentMax = array for value in array[1..<array.count] { if value currentMax { currentMax = value } } return (currentMin, currentMax)}if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("Minimum value is (bounds.min)οΌMaximum value is (bounds.max)")}\nThe output of the above program execution is:\n\nMinimum value is -6οΌMaximum value is 109\n\n* * *\n\n## Functions Without Return Values\n\nHere is another version of the tutorial(_:) function. This function takes the Tutorial official website URL parameter, does not specify a return type, and directly prints the String value instead of returning it:\n\nimport Cocoa func tutorial(site: String) { print("Official Website:(site)")} tutorial(site: "")\nThe output of the above program execution is:\n\nOfficial Website:\n\n* * *\n\n## Function Parameter Names\n\nFunction parameters have both an external parameter name and a local parameter name.\n\n### Local Parameter Names\n\nLocal parameter names are used within the implementation of the function.\n\nfunc sample(number: Int) { println(number)}\nIn the above example, number is a local parameter name, which can only be used inside the function body.\n\nimport Cocoa func sample(number: Int) { print(number)} sample(number: 1) sample(number: 2) sample(number: 3)\nThe output of the above program execution is:\n\n123\n### External Parameter Names\n\nYou can specify an external parameter name before the local parameter name, separated by a space. External parameter names are used to pass parameters to the function when it is called.\n\nAs follows, you can define the following two function parameter names and call it:\n\nimport Cocoa func pow(firstArg a: Int, secondArg b: Int) -> Int { var res = a for _ in 1.. Note\n> \n> If you provide external parameter names, the function must use the external parameter names when called.\n\n* * *\n\n## Variadic Parameters\n\nVariadic parameters can accept zero or more values. When calling a function, you can use variadic parameters to specify function parameters whose quantity is uncertain.\n\nVariadic parameters are defined by adding (...) after the variable type name.\n\nimport Cocoa func vari(members: N...){ for i in members { print(i) }} vari(members: 4,3,5) vari(members: 4.5, 3.1, 5.6) vari(members: "Google", "Baidu", "Tutorial")\nThe output of the above program execution is:\n\n4354.53.15.6GoogleBaiduTutorial\n\n* * *\n\n## Constants, Variables, and I/O Parameters\n\nBy default, parameters defined in a function are constant parameters, meaning you can only query and use this parameter, but cannot change its value.\n\nIf you want to declare a variable parameter, you can add the inout keyword before the parameter definition, so that the value of this parameter can be changed.\n\nFor example:\n\nfunc getName(_ name: inout String).........\nAt this point, the name value can be changed within the function.\n\nBy default, parameter passing is call-by-value, not call-by-reference. Therefore, changing the passed parameter inside the function does not affect the original parameter. Only a copy of this parameter is passed in.\n\nWhen the passed parameter is used as an input-output parameter, you need to add an & sign before the parameter name, indicating that this value can be modified by the function.\n\n### Example\n\nimport Cocoa func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA }var x = 1var y = 5 swapTwoInts(&x, &y)print("x Current value (x), y Current value (y)")\nThe swapTwoInts(_:_:) function simply swaps the values of a and b. The function first stores the
YouTip