Swift Functions

Swift Functions

Define reusable code with parameters and return values; control labels, mutation with inout, defaults, and variadics.


Defining and Calling Functions

Use func to define a function with a name, parameters, and return value.

Syntax:

  • func name(param: Type) -> Return
  • Call with name(param:)

Example

func greet(name: String) -> String {
  return "Hello, \(name)!"
}
print(greet(name: "Swift"))

This example defines a function named greet that takes a String parameter and returns a greeting message.


Parameters and Return Values

Use func to define a function with multiple parameters and a return value.

Syntax:

  • func name(param1: Type, param2: Type) -> Return
  • Multiple params: Separate by commas; annotate types.
  • Parameter labels: External names shown at call sites; use _ to omit.
  • Return type: Use ->; omit for Void.

Example

func add(_ a: Int, _ b: Int) -> Int { a + b }
print(add(2, 3))

This example omits external parameter labels with _ and returns the sum as an Int.



Inout, Default Values, Variadics

Use func to define a function with multiple parameters and a return value.

Syntax:

  • func name(param: inout Type, default: Type = value)
  • func name(param: Type...)

Example

func increment(_ value: inout Int, by step: Int = 1) {
  value += step
}
var x = 10
increment(&x)
print(x) // 11

func sum(_ nums: Int...) -> Int { nums.reduce(0, +) }
print(sum(1,2,3))

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *