티스토리 뷰

Swift

[Swift] Functions (함수)

learner._.Kio 2021. 2. 20. 01:10

목차

  • Functions (함수)
  • Return Values (리턴 값)
  • Parameters (매개변수)
  • Argument Label
  • In-Out Parameters (입출력 매개변수)
  • Function Notation (함수 표기법)
  • Discardable Result (버릴 수 있는 결과)
  • Implicit Return




Functions (함수)

함수는 특정 기능을 수행하는 코드 조각이다.

Functions (함수) 종류

  • Calling Functions (함수 호출)

    Swift에는 Swift Standard Library라는 게 내장되어 있는데, 다양한 기본 함수가 구현되어 있어서 편하게 함수를 가져와서 사용할 수 있다.

  • Defining Functions (함수 정의)

    필요한 함수를 직접 만드는 방법이다.

Calling Functions (함수 호출) 선언

functionName(parameters)
print("Hello, world")
// parameters :: Hello, world

Defining Functions (함수 정의) 선언

func name(parameters) -> ReturnType {
    statements
}
// 함수이름은 lowCamel 법칙으로 짓는다.
func sayHello() {
    print("Hello, World")
}
sayHello()  // Hello, World




Return Values (리턴 값)

Return Values (리턴 값) 선언

func name(parameters) -> ReturnType {
    statements
      return expression
}

Return Values (리턴 값) 예시

func add() -> Int {
    return 1 + 2
}

let r = add()    // r = 3

if add() == 3 {
    print("3, Three")    // 3, Three
}
func doSomething() {
    let random = Int.random(in: 1...10)

    if random % 2 == 1 {
        return
    }
    print(random)
}
doSomething()    // radom 숫자에 따른 값이 출력된다.



Parameters (매개변수)

Parameters 선언

func name(parameters) -> ReturnType {
    statements
}

(name: Type, name: Type)

Parameters Calling Functions (Parameters 함수 호출)

functionName(paramName: expr)
func add(a: Int, b: Int) -> Int {
    return a + b
}
// a,b :: Formal Parameters

add(a: 1, b: 2)
// a,b :: Actual Parameters = Arguments(인자)

Parameters Default Value (Parameters 기본값)

func sayHello(to: String = "World") {
    print("Hello, \(to)")
}

sayHello(to: "Swift")   // Hello, Swift
sayHello()              // Hello, World




Argument Label

Argument Label 선언

(name: Type)
// name : Argument Label
// Type : Parameter Name

(label name: Type)
// name : Parameter Name
// label : Argument Lable

Argument Label 예시

sayHello(name: "World")
// name : Argument Label
// World : Actual Parameter == Argument

// A
func greeting(name: String) {
   print("Hello, \(name)")
}

// B
func greeting(to name: String) {
    print("Hello, \(name)")
// Use of unresolved identifier 'to'
// 'Argument Label'은 함수로 호출할 때 사용하는 이름이고, 함수 내에서 parameter로 접근하는 이름은 아니다.
}

// A,B 같은 이름의 함수지만, 함수 이름에 Argument Label이 포함되어 있기 때문에 error가 발생하지 않음.
// A - greeting(name:)
// B - greeting(to:)

Wildcard Pattern ('_')

func greeting(_ name: String) {
    print("Hello, \(name)")
}

greeting("World")    // Hello, World




In-Out Parameters (입출력 매개변수)

Basic Parameters

var num1 = 13
var num2 = 25

func changeNumber(_ a: Int, with b: Int) {
    /* error
      let tmp = a
      a = b
      b = tmp */
}
changeNumber(num1, with: num2)
// changeNumber을 통해 num1, num2를 보내더라도 
// 복사본을 보내는 것이기 때문에 num1, num2 자체의 값은 변하지 않는다.

In-Out Parameters 선언

(name: inout Type)
functionName(argLabel: &expr)

In-Out Parameters 예시

var num1 = 13
var num2 = 25

func changeNumber(_ a: inout Int, with b: inout Int) {
    let tmp = a
    a = b
    b = tmp
}
print(num1) // 13
print(num2) // 25

changeNumber(&num1, with: &num2)    // 주소값
// copy-in : 입출력 parameters의 값을 복사하여 swapNumber 함수로 보낸다.
// copy-out : 함수가 종료되면 함수 내부에서 변경된 값이 Argument로 전달한 변수에 복사된다.  

print(num1) // 25
print(num2) // 13

In-Out Parameters 특징

  • 동일한 변수를 2번 이상 보내는 것은 불가능하다.

  • Let으로 선언한 상수는 바꿀 수 없다.

  • 리터럴을 직접 전달하면 오류가 발생한다.

    changeNumber(&13, with: &25) // error
  • 항상 메모리를 가진 변수를 전달해야 한다.

  • 가변 parameters에서 사용할 수 없다.

    func sum(of nums : inout Int...) {    // error
            // statements   
    }




Function Notation (함수 표기법)

functionName(label:)
functionName(label:label:)
functionName
// parameter가 없다면 ()빈 괄호를 쓰기도 하는데, 코드 내에서 함수표기법을 사용할 때는 괄호를 빼야한다.
func sayHello() {
    print("Hello, World")
}
sayHello    // 함수 표기법으로 함수 지칭
sayHello()  // 함수 호출


func sayHello(to name: String) {
    print("Hello, \(name)")
}
sayHello(to:)   // 함수 표기법으로 함수 지칭
sayHello(to: "World") // 함수 호출


func sayHello(_ name: String) {
    print("Hello, \(name)")
}
sayHello(_:)    // 함수 표기법으로 함수 지칭
sayHello(_: "World")    // 함수 호출




Implicit Return

Explicit Return (return 존재)

func name(parameters) -> ReturnType {
    statements
    return expression
}

Implicit Return (return 생략)

func name(parameters) -> ReturnType {
    single_expression // 단일 표현식
}

Implicit Return 예시

func add(a: Int, b: Int) -> Int {
   return a + b     // single_expression(단일표현식)이라면 return을 생략할 수 있다.
}
add(a: 1, b: 2) // 3


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




Discardable Result (버릴 수 있는 결과)

Discardable Result 선언 및 예시

import UIKit

// @discardableResult
// 결과를 리턴하지 않는 값에서는 아무런 의미가 없다.
func doSomething() {
   print("Something secret")
}

@discardableResult
/*
경고 메시지를 숨기고 싶다면 Discardable Result 특성을 사용한다.
함수가 리턴한 결과를 사용하지 않고 버리거나 무시한다는 뜻이다.
 */
func saySomething() -> String {
   return "Hello"
}

class ViewController: UIViewController {

   override func viewDidLoad() {
      super.viewDidLoad()

      doSomething()

      saySomething()    // 리턴한 값을 사용하지 않았다는 경고메시지
      _ = saySomething() // discardableResult를 사용하지 않고 경고메시지 숨기기
   }
}
댓글