소소한개발팁
article thumbnail
반응형

Defining and Calling Functions

 

- Swift에서는 보통 아래와 같이 함수를 생성할 수 있습니다.

 

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

 

- 위의 함수를 호출할 때는 아래의 예시와 같습니다.

 

print(greet(person: "Anna"))
// Prints "Hello, Anna!"
print(greet(person: "Brian"))
// Prints "Hello, Brian!"

 

- 위의 함수를 축약한 것은 아래의 예시와 같습니다.

 

func greetAgain(person: String) -> String {
  return "Hello again, " + person + "!"
}
print(greetAgain(person: "Anna"))
// Prints "Hello again, Anna!"

 

 

Function Parameters and Return Values

- 매개변수가 없는 함수는 아래와 같이 사용할 수 있습니다.

 

func sayHelloWorld() -> String {
  return "hello, world"
}
print(sayHelloWorld())
// Prints "hello, world"

 

- 매개변수가 여러 개인 함수는 아래와 같이 사용할 수 있습니다.

 

func greet(person: String, alreadyGreeted: Bool) -> String {
 if alreadyGreeted {
  return greetAgain(person: person)
 } else {
  return greet(person: person)
 }
}
print(greet(person: "Tim", alreadyGreeted: true))
// Prints "Hello again, Tim!"

 

- 반환 값이 없는 함수는 아래와 같이 ( -> ) 사용하지 않고 사용할 수 있습니다.

 

func greet(person: String) {
  print("Hello, \(person)!")
}
greet(person: "Dave")
// Prints "Hello, Dave!"

 

- 반환 값을 무시할 수 있는 경우는 아래의 예시와 같이 사용할 수 있습니다.

 

func printAndCount(string: String) -> Int {
  print(string)
  return string.count
}
func printWithoutCounting(string: String) {
  let _ = printAndCount(string: string)
}
printAndCount(string: "hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting(string: "hello, world")
// prints "hello, world" but doesn't return a value

 

- 반환 여러 개인 경우는 아래의 예시와 같이 사용할 수 있습니다.

 

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(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// Prints "min is -6 and max is 109"

 

 

Optional Tuple Return Types

- 위에서 선언한 minMax() 함수의 매개변수에 nil 값이 올 경우를 대비한 예시입니다.

 

func minMax(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 = minMax(array: [8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
// Prints "min is -6 and max is 109"

 

 

Functions With an Implicit Return 

- 암시적으로 리턴이 있는 형식의 예시입니다.

 

func greeting(for person: String) -> String {
 "Hello, " + person + "!"
}
print(greeting(for: "Dave"))
// Prints "Hello, Dave!"

func anotherGreeting(for person: String) -> String {
 return "Hello, " + person + "!"
}
print(anotherGreeting(for: "Dave"))
// Prints "Hello, Dave!"

 

 

Function Argument Labels and Parameter Names  

함수를 작성하고 매개 변수의 이름을 작성할 때는 고유한 이름을 가지도록 하여 가독성을 높여주는 게 좋습니다. 아래는 이에 대한 예시입니다.

 

func someFunction(firstParameterName: Int, secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument values for the first and second parameters.
}
someFunction(firstParameterName: 1, secondParameterName: 2)

 

 

Specifying Argument Labels 

매개변수 이름 앞에 공백으로 구분된 인수 레이블을 사용하는 경우의 예시입니다.

 

func someFunction(argumentLabel parameterName: Int) {
// In the function body, parameterName refers to the argument value
// for that parameter.
}
func greet(person: String, from hometown: String) -> String {
  return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill! Glad you could visit from Cupertino."

 

 

Omitting Argument Labels 

매개변수에 대한 인수 레이블을 사용하지 않으려면 아래의 예시와 같이 ( _ ) 를 사용하면 됩니다.

 

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument values for the first and second parameters.
}
someFunction(1, secondParameterName: 2)

 

 

Default Parameter Values 

매개변수에 기본 값을 할당 할 수 있습니다. 아래의 예시와 같습니다.

 

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// If you omit the second argument when calling this function, then
// the value of parameterWithDefault is 12 inside the function body.
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12

 

 

Variadic Parameters 

- 변수 매개변수는 지정된 유형의 0개 이상의 값을 허용할 수 있습니다. 아래의 예시와 같습니다.

 

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

 

 

In-Out Parameters

함수의 매개변수 값을 함수의 본문 내에서 변경하려고 하면 컴파일 시간 오류가 발생합니다. 이는 실수로 매개 변수의 값을 변경할 수 없음을 의미하며 함수에서 매개 변수의 값을 수정하고 함수 호출이 종료된 후에도 이러한 변경 사항이 지속되도록 하려면 대신 해당 매개 변수를 in-out 매개 변수로 정의해야 합니다. 아래는 이에 대한 예시입니다.

 

func swapTwoInts(_ a: inout Int, _ b: inout 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"

 

 

 Function Types 

- 함수에는 매개변수 유형과 함수의 반환 유형으로 구성된 특정 기능 유형이 있습니다. 아래는 이에 대한 예시입니다.

 

func addTwoInts(_ a: Int, _ b: Int) -> Int {
  return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
  return a * b
}

 

- 이 두 함수의 유형은 (Int, Int) -> Int 이며 이는 두 개의 Int형 매개변수를 가지며 Int 형 값을 반환하는 함수라는 의미입니다. 매개 변수나 반환 값이 없는 함수의 예는 아래와 같습니다.

 

func printHelloWorld() {
  print("hello, world")
}

 

 

Using Function Types 

- 함수의 값으로 변수를 생성할 수 있으며 아래의 예시와 같습니다.

 

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

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

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

let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int

 

 

Function Types as Parameter Types 

- 매개 변수 값을 함수로 지정할 수 있으며 아래의 예시와 같습니다.

 

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

 

 

Function Types as Return Types 

- 함수 값을 다른 함수의 반환 유형으로 사용할 수 있습니다. 아래의 예시와 같습니다.

 

func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: 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!

 

 

Nested Functions

- 함수 안에서 다른 함수를 사용하는 예시입니다.

 

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

var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function

while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!

 

 

내용은 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html 를 보면서 작성하였고 원문으로 작성된 내용을 옮기다 보니 이상한 부분이 있을 수 있습니다. 자세한 내용은 위의 링크를 확인해주시기 바랍니다.

반응형
profile

소소한개발팁

@개발자 뱅

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!