λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

🍎 iOS/Swift

[Swift] ν•¨μˆ˜(Function) - κΈ°λ³Έ

728x90

βœ”οΈ ν•¨μˆ˜μ˜ μ •μ˜

μ• ν”Œ κ°œλ°œλ¬Έμ„œμ— λ”°λ₯΄λ©΄ Swiftμ—μ„œ ν•¨μˆ˜λŠ” λ‹€μŒκ³Ό 같이 μ •μ˜λœλ‹€.

 

[Definition]

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.

 

ν•¨μˆ˜(Functions)λŠ” νŠΉμ • μž‘μ—…μ„ μˆ˜ν–‰ν•˜λŠ” 자체적으둜 ν¬ν•¨λœ(self-contained) μ½”λ“œ 덩어리(chunks) 이닀. ν•¨μˆ˜κ°€ 무엇을 ν•˜λŠ”μ§€ 식별가λŠ₯ν•œ 이름을 μ£Όκ³ , μ΄λŸ¬ν•œ 이름은 ν•„μš”ν• λ•Œ μž‘μ—…μ„ μˆ˜ν–‰ν•˜κΈ° μœ„ν•΄ 호좜(call)ν•˜μ—¬ μ‚¬μš©λœλ‹€.


- 원문 : μ• ν”Œ 개발 λ¬Έμ„œ Swift 4.2 Language Guide - Functions

 

Contents

   1. ν•¨μˆ˜μ˜ μ„ μ–Έ, ν˜ΈμΆœν•˜κΈ°    

     1 - 1. ν•¨μˆ˜μ„ μ–Έμ˜ κΈ°λ³Έν˜•νƒœ (Defaining Functions)
     1 - 2. ν•¨μˆ˜ 호좜 (Calling Functions)


   2. ν•¨μˆ˜μ˜ ν˜•νƒœ
    2 - 1. λ°˜ν™˜κ°’μ΄ μ—†λŠ” ν•¨μˆ˜ (Functions Without Return Values)
    2 - 2. λ§€κ°œλ³€μˆ˜κ°€ μ—†λŠ” ν•¨μˆ˜ (Functions Without Parameters)
    2 - 3. λ°˜ν™˜κ°’κ³Ό λ§€κ°œλ³€μˆ˜κ°€ μ—†λŠ” ν•¨μˆ˜ (Function Without Return Values and Parameters)
    2 - 4. λ§€κ°œλ³€μˆ˜κ°€ μ—¬λŸ¬κ°œμΈ ν•¨μˆ˜ (Function With Mulitple Parameters)
    2 - 5. λ°˜ν™˜κ°’μ΄ μ—¬λŸ¬κ°œμΈ ν•¨μˆ˜ (Function With Mulitple Return Values)

🍎  ν•¨μˆ˜(Function)의 μ„ μ–Έ, ν˜ΈμΆœν•˜κΈ°

[ν•¨μˆ˜μ˜ μ„ μ–Έ(Defaining Functions)]

Swiftμ—μ„œ ν•¨μˆ˜λ₯Ό μ •μ˜ν•  λ•ŒλŠ”κ°€μž₯ μ•žμ— func ν‚€μ›Œλ“œλ₯Ό 뢙이고 (person: String) νŒŒλΌλ―Έν„°μ™€ ν˜• 그리고 -> String ν˜•νƒœλ‘œ λ°˜ν™˜ν˜•μ„ μ •μ˜ν•œλ‹€.

이 λ•Œ, ν•¨μˆ˜μ•ˆμ˜ 틀을 λ§€κ°œλ³€μˆ˜(Parameters) νƒ€μž…, ν‹€ μ•ˆμ— λ“€μ–΄κ°€λŠ” μ‹€μ œ 값을 인자(Arguments)라 ν•œλ‹€.

func <ν•¨μˆ˜μ΄λ¦„>(<λ§€κ°œλ³€μˆ˜1이름>: <λ§€κ°œλ³€μˆ˜1νƒ€μž…>, <λ§€κ°œλ³€μˆ˜2이름>: <λ§€κ°œλ³€μˆ˜2νƒ€μž…> ...) -> <λ°˜ν™˜νƒ€μž…> {
    <ν•¨μˆ˜ κ΅¬ν˜„λΆ€>
    return <λ°˜ν™˜κ°’>
}
func greet(person: String, age: Int) -> String {
    let greeting = "Hello, " + person + "I'm" + String(age) + "!"
    return greeting
}

[ν•¨μˆ˜ 호좜(Calling Functions)]

ν•¨μˆ˜μ΄λ¦„(λ§€κ°œλ³€μˆ˜1이름: μž…λ ₯κ°’, λ§€κ°œλ³€μˆ˜2이름: μž…λ ₯κ°’ ...)
print(greet(person: "Anna", age: 20))

🍎  ν•¨μˆ˜(Function)의 ν˜•νƒœ

2 - 1. λ°˜ν™˜κ°’이 μ—†λŠ” ν•¨μˆ˜ (Functions Without Return Values)

ν•¨μˆ˜λŠ” λ°˜ν™˜κ°’μ„ μƒλž΅ν•  수 μžˆλ‹€. λ°˜ν™˜κ°’μ΄ μ—†κΈ° λ•Œλ¬Έμ— -> κ³Ό ν•¨κ»˜ λ°˜ν™˜νƒ€μž…λ„ μƒλž΅ κ°€λŠ₯ν•˜λ‹€.

func ν•¨μˆ˜μ΄λ¦„(λ§€κ°œλ³€μˆ˜1이름: λ§€κ°œλ³€μˆ˜1νƒ€μž…, λ§€κ°œλ³€μˆ˜2이름: λ§€κ°œλ³€μˆ˜2νƒ€μž… ...) -> Void {
    /* ν•¨μˆ˜ κ΅¬ν˜„λΆ€ */
}
// void μƒλž΅κ°€λŠ₯
func ν•¨μˆ˜μ΄λ¦„(λ§€κ°œλ³€μˆ˜1이름: λ§€κ°œλ³€μˆ˜1νƒ€μž…, λ§€κ°œλ³€μˆ˜2이름: λ§€κ°œλ³€μˆ˜2νƒ€μž… ...) {
}

 

func printMyName(name: String) -> Void {
    print(name)
}

//Void μƒλž΅ κ°€λŠ₯
func printMyName(name: String){
    print(name)
}
// 호좜
printYourName(name: "lee")
// >> lee

2 - 2. νŒŒλΌλ―Έν„°κ°€ μ—†λŠ” ν•¨μˆ˜ (Functions Without Parameters)

ν•¨μˆ˜λŠ” μž…λ ₯ λ§€κ°œλ³€μˆ˜λ₯Ό μƒλž΅ν•  수 μžˆλ‹€. μƒλž΅ν•˜λ”λΌλ„ ν•¨μˆ˜ 이름 λ’€μ˜ μ†Œκ΄„ν˜Έ()λŠ” μƒλž΅ν•  수 μ—†λ‹€.

func ν•¨μˆ˜μ΄λ¦„() -> λ°˜ν™˜νƒ€μž… {
    /* ν•¨μˆ˜ κ΅¬ν˜„λΆ€ */
    return λ°˜ν™˜κ°’
}

 

func maximumIntegerValue() -> Int {
    return Int.max
}
// 호좜
maximumIntegerValue()
// >> 9223372036854775807

 

 2 - 3. λ°˜ν™˜κ°’κ³Ό λ§€κ°œλ³€μˆ˜κ°€ μ—†λŠ” ν•¨μˆ˜ (Function Without Return Values and Parameters)

λ¬Όλ‘  λ°˜ν™˜κ°’κ³Ό μž…λ ₯ λ§€κ°œλ³€μˆ˜ λͺ¨λ‘ μƒλž΅ν•  수 μžˆλ‹€.

func ν•¨μˆ˜μ΄λ¦„() -> Void { // -> Void μƒλž΅ κ°€λŠ₯
    /* ν•¨μˆ˜ κ΅¬ν˜„λΆ€ */
    return
}

 

// ν•¨μˆ˜ κ΅¬ν˜„μ΄ 짧은 경우 가독성을 ν•΄μΉ˜μ§€ μ•ŠλŠ” λ²”μœ„μ—μ„œ μ€„λ°”κΏˆμ„ ν•˜μ§€ μ•Šκ³  ν•œ 쀄에 ν‘œν˜„ν•΄λ„ λ¬΄κ΄€ν•˜λ‹€.
func hello() -> Void { print("hello") }

// 호좜
hello()
// >> hello

2 - 4. λ§€κ°œλ³€μˆ˜κ°€ μ—¬λŸ¬κ°œμΈ ν•¨μˆ˜ (Function With Mulitple Parameters)

ν•¨μˆ˜λŠ” 콀마둜 κ΅¬λΆ„λœ μ—¬λŸ¬κ°œμ˜ νŒŒλΌλ―Έν„°λ₯Ό κ°€μ§ˆ 수 μžˆλ‹€.

func greet(person: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return "Hello, " + person + ". again!"
    }else{
        return "Hello, " + person + "!"
    }
}
//호좜
print(greet(person: "Tim", alreadyGreeted: false))

2 - 5. λ°˜ν™˜κ°’μ΄ μ—¬λŸ¬κ°œμΈ ν•¨μˆ˜ (Function With Mulitple Return Values)

ν•¨μˆ˜λŠ” λ°˜ν™˜ νƒ€μž…μ„ νŠœν”Œ 값을 μ‚¬μš©ν•  수 있으며 ν•˜λ‚˜μ˜ μ§‘ν•©μœΌλ‘œ 된 닀쀑 값을 λ°˜ν™˜ν•œλ‹€.

func sum(_ num1: Int, _ num2: Int) -> (Int, Int, Int){
    return (num1, num2, num1+num2)
}

var sumRes = sum(20, 30)
print(sumRes)
// >> (20, 30, 50) λͺ¨λ“  κ°’ 좜λ ₯

μ›ν•˜λŠ” νŠΉμ • λ°˜ν™˜κ°’μ„ 좜λ ₯ν•˜κ³  싢은 κ²½μš°μ—λŠ” 두가지 방법이 μžˆλ‹€.

  1. index 번호둜 μ ‘κ·Όν•˜λŠ” 방법

  2. λ°˜ν™˜κ°’μ˜ λ³€μˆ˜λ₯Ό μ„ μ–Έν•˜μ—¬ λ³€μˆ˜λ‘œ μ ‘κ·Όν•˜λŠ” 방법

func sum(_ num1: Int, _ num2: Int) -> (Int, Int, res: Int){
    return (num1, num2, num1+num2)
}

var sumRes = sum(20, 30)

// 1. index 번호둜 μ ‘κ·Ό
print(sumRes.0)
// >> 20

// 2. λ°˜ν™˜κ°’μ˜ λ³€μˆ˜λ‘œ μ ‘κ·Ό
print(sumRes2.res)
// >> 50

🍎 λ§€κ°œλ³€μˆ˜μ˜ κΈ°λ³Έ κ°’(default value) μ„€μ •ν•˜κ³  호좜 μ‹œ μƒλž΅ν•˜κΈ°

  • λ§€κ°œλ³€μˆ˜μ— 미리 값을 섀정해놓을 수 있음
  • 기본값을 κ°–λŠ” λ§€κ°œλ³€μˆ˜λŠ” λ§€κ°œλ³€μˆ˜ λͺ©λ‘ 쀑에 λ’€μͺ½μ— μœ„μΉ˜
  • λ§€κ°œλ³€μˆ˜ 기본값을 κ°€μ§€λŠ” λ§€κ°œλ³€μˆ˜λŠ” 호좜 μ‹œ μƒλž΅ κ°€λŠ₯
  • _λ₯Ό μ‚¬μš©ν•˜μ—¬ λ§€κ°œλ³€μˆ˜ μƒλž΅ κ°€λŠ₯
func greeting(friend: String, me: String = "lee") {
    print("Hello \(friend)! I'm \(me)")
}

//meλŠ” 기본값이 μžˆμœΌλ―€λ‘œ μƒλž΅ κ°€λŠ₯!
greeting(friend: "hana") // Hello hana! I'm lee
greeting(friend: "john", me: "eric") // Hello john! I'm eric

//(_)μ‚¬μš©ν•˜μ—¬ parameter 이름 μƒλž΅ν•˜κΈ°
func greeting(_ friend: String, from me: String) {
    print("Hello \(friend)! I'm \(me)")
}
greeting("Bill", from: "")	//Hello Bill! I'm

🍎 μ „λ‹¬μΈμž λ ˆμ΄λΈ”

  • λ§€κ°œλ³€μˆ˜κ°€ μ–΄λ–€ 역할을 ν•  건지 λͺ…ν™•ν•˜κ²Œ ν•΄ 쀌
  • λ§€κ°œλ³€μˆ˜ 이름 μ•žμ— μž‘μ„±
  • 곡백으둜 ꡬ뢄
//μœ„ μ½”λ“œμ˜ greetingκ³Ό λ‹€λ₯Έ ν•¨μˆ˜
//μ „λ‹¬μΈμž λ ˆμ΄λΈ” : to, from
func greeting(to friend: String, from me: String) {
    print("Hello \(friend)! I'm \(me)")
    // μ „λ‹¬μΈμžμ˜ 역할을 ν‘œν˜„ν•˜κ³  싢을 λ•Œ μ‚¬μš©
    // ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ „λ‹¬μΈμž(to, from) λ₯Ό μ‚¬μš©ν•  λ•Œμ—λŠ” λ§€κ°œλ³€μˆ˜ 이름을 μ‚¬μš©ν•©λ‹ˆλ‹€
}

// ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œμ—λŠ” μ „λ‹¬μΈμž λ ˆμ΄λΈ”μ„ μ‚¬μš©
greeting(to: "hana", from: "lee") // Hello hana! I'm lee

🍎 κ°€λ³€ λ§€κ°œλ³€μˆ˜

  • 전달받을 κ°’μ˜ 개수λ₯Ό μ•ŒκΈ° μ–΄λ €μšΈ λ•Œ μ‚¬μš©ν•  수 μžˆλ‹€.
  • κ°€λ³€ λ§€κ°œλ³€μˆ˜λŠ” ν•¨μˆ˜λ‹Ή ν•˜λ‚˜λ§Œ κ°€μ§ˆ 수 μžˆλ‹€.
  • 항상 맨 뒀에 μœ„μΉ˜ν•˜λ©° ...으둜 ν‘œν˜„
//전달 인자 μ—¬λŸ¬κ°œ 받을 수 있음(ν•œμ •X)
//...으둜 ν‘œν˜„
func sayHelloToFriends(me: String, friends: String...) -> String {
    return "Hello \(friends)! I'm \(me)!"
}

print(sayHelloToFriends(me: "lee", friends: "one", "two", "three"))
// Hello ["one", "two", "three"]! I'm lee!

//인자 μ•ˆ λ„£μœΌλ €λ©΄ μ „λ‹¬μΈμž μ•„μ˜ˆ μƒλž΅
print(sayHelloToFriends(me: "lee"))
// Hello []! I'm lee!

//λ§€κ°œλ³€μˆ˜ 써놓고 κ°’ μ•ˆλ„£μœΌλ©΄ 였λ₯˜ λ°œμƒ
//print(sayHelloToFriends(me: "lee", friends: nil))
//print(sayHelloToFriends(me: "lee", friends: ))

βœ”οΈ κ°€λ³€ λ§€κ°œλ³€μˆ˜λ‘œ 평균 κ΅¬ν•˜κΈ°

func avg1(score: Int ...) -> Double{
    var total = 0
    for i in score{ //κ°€λ³€ μΈμžμ— λ„˜κΈ΄ 값은 μ μ ˆν•œ νƒ€μž…μ˜ λ°°μ—΄λ‘œ λ§Œλ“€μ–΄μ§.
        total += i
    }
    return Double(total)/Double(score.count)
}
var result = avg1(score: 1, 2, 3)    //2

var a: [Int] = []
func avg2(score: Int ...) -> Double{
    a = score   // 배열에 λŒ€μž… κ°€λŠ₯
    var total = 0
    for i in score{ //κ°€λ³€ μΈμžμ— λ„˜κΈ΄ 값은 μ μ ˆν•œ νƒ€μž…μ˜ λ°°μ—΄λ‘œ λ§Œλ“€μ–΄μ§.
        total += i
    }
    return Double(total)/Double(score.count)
}
var result1 = avg2(score: 1, 2, 3)  //2
//κ°€λ³€μΈμž 좜λ ₯
print("scores : \(a)")  //scores : [1, 2, 3]
print("first score : \(a[0])") //first score : 1

🍎 λ°μ΄ν„° νƒ€μž…μœΌλ‘œμ„œμ˜ ν•¨μˆ˜

  • μ–Έμ œλ‚˜ ν•¨μˆ˜λŠ” parameter, return 값에 λ”°λ₯Έ νŠΉμ • νƒ€μž…μ„ 가진닀.
  • Swiftμ—μ„œλŠ” ν•¨μˆ˜ νƒ€μž…μ— 따라 λ³€μˆ˜λ₯Ό μ •μ˜ν•  수 μžˆλ‹€.
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}

var function : (Int, Int) -> Int
function = multiplyTwoInts(_:_:)
function(2, 3)

 

βœ”οΈ λ§€κ°œλ³€μˆ˜ νƒ€μž…μ²˜λŸΌ μ‚¬μš©ν•˜λŠ” ν•¨μˆ˜ νƒ€μž…

  • (Int, Int) -> (Int)와 같은 ν•¨μˆ˜ νƒ€μž…μ„ λ‹€λ₯Έ ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜λ‘œ μ‚¬μš©ν•  μˆ˜λ„ μžˆλ‹€.
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(multiplyTwoInts, 3, 5)

βœ”οΈ λ°˜ν™˜ νƒ€μž…μ²˜λŸΌ μ‚¬μš©ν•˜λŠ” ν•¨μˆ˜ νƒ€μž…

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
}
λ°˜μ‘ν˜•