πŸ‘©πŸ»‍πŸ’»/Swift

7. ν•¨μˆ˜ (μƒˆλ‘­κ²Œ μ•Œκ²Œλœ 점) - iOS ν”„λ‘œκ·Έλž˜λ°μ„ μœ„ν•œ μŠ€μœ„ν”„νŠΈ 기초

reujusong 2020. 6. 17. 16:13

 - 전달 인자 λ ˆμ΄λΈ”

  • ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ ν•¨μˆ˜ μ‚¬μš©μžμ˜ μž…μž₯μ—μ„œ λ§€κ°œλ³€μˆ˜μ˜ 역할을 μ’€ 더 λͺ…ν™•ν•˜κ²Œ ν‘œν˜„ν•˜κ³ μž ν•  λ•Œ μ‚¬μš©ν•œλ‹€.
  • μ „λ‹¬μΈμž λ ˆμ΄λΈ”μ€ λ³€κ²½ν•˜μ—¬ λ™μΌν•œ μ΄λ¦„μ˜ ν•¨μˆ˜λ₯Ό μ€‘λ³΅μœΌλ‘œ 생성가λŠ₯ν•˜λ‹€.

 

func ν•¨μˆ˜μ΄λ¦„(μ „λ‹¬μΈμž λ ˆμ΄λΈ” λ§€κ°œλ³€μˆ˜1이름: λ§€κ°œλ³€μˆ˜1νƒ€μž…, μ „λ‹¬μΈμž λ ˆμ΄λΈ” λ§€κ°œλ³€μˆ˜2이름: λ§€κ°œλ³€μˆ˜2νƒ€μž… ...) -> λ°˜ν™˜νƒ€μž… {
    /* ν•¨μˆ˜ κ΅¬ν˜„λΆ€ */
    return
}

// ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ „λ‹¬μΈμžλ₯Ό μ‚¬μš©ν•  λ•Œμ—λŠ” λ§€κ°œλ³€μˆ˜ 이름을 μ‚¬μš©ν•œλ‹€
func greeting(to friend: String, from me: String) {
    print("Hello \(friend)! I'm \(me)")
}

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

 

Tip : ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œλŠ” λ§€κ°œλ³€μˆ˜ 이름을 μ‚¬μš©ν•˜κ³  ν•¨μˆ˜ ν˜ΈμΆœμ‹œμ—λŠ” μ „λ‹¬μΈμž λ ˆμ΄λΈ”μ„ μ‚¬μš©ν•œλ‹€.

 

 

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

  • 전달 받을 κ°’μ˜ 개수λ₯Ό μ•ŒκΈ° μ–΄λ €μšΈ λ•Œ μ‚¬μš©ν•œλ‹€.
  • κ°€λ³€ λ§€κ°œλ³€μˆ˜λŠ” ν•¨μˆ˜λ‹Ή ν•˜λ‚˜λ§Œ κ°€μ§ˆ 수 μžˆλ‹€.
  • 기본값이 μžˆλŠ” λ§€κ°œλ³€μˆ˜μ™€ 같이 κ°€λ³€ λ§€κ°œλ³€μˆ˜ μ—­μ‹œ λ§€κ°œλ³€μˆ˜ λͺ©λ‘ 쀑 λ’€μͺ½μ— μœ„μΉ˜ν•˜λŠ” 것이 μ’‹λ‹€.

 

//func ν•¨μˆ˜μ΄λ¦„(λ§€κ°œλ³€μˆ˜1이름: λ§€κ°œλ³€μˆ˜1νƒ€μž…, μ „λ‹¬μΈμž λ ˆμ΄λΈ” λ§€κ°œλ³€μˆ˜2이름: λ§€κ°œλ³€μˆ˜2νƒ€μž…...) -> λ°˜ν™˜νƒ€μž… {
//    /* ν•¨μˆ˜ κ΅¬ν˜„λΆ€ */
//    return
//}

func sayHelloToFriends(me: String, friends: String...) -> String {
    return "Hello \(friends)! I'm \(me)!"
}
print(sayHelloToFriends(me: "kdgt", friends: "hana", "eric", "wing"))
// Hello ["hana", "eric", "wing"]! I'm kdgt!

print(sayHelloToFriends(me: "kdgt"))
// Hello []! I'm kdgt!

 

Tip : κ°€λ³€ λ§€κ°œλ³€μˆ˜μ—λŠ” nil을 μ“Έ 수 μ—†λ‹€.

 

 - 데이터 νƒ€μž…μœΌλ‘œμ„œμ˜ ν•¨μˆ˜

  • μŠ€μœ„ν”„νŠΈλŠ” ν•¨μˆ˜ν˜• ν”„λ‘œκ·Έλž˜λ° νŒ¨λŸ¬λ‹€μž„μ„ ν¬ν•¨ν•˜λŠ” 닀쀑 νŒ¨λŸ¬λ‹€μž„ μ–Έμ–΄μ΄λ―€λ‘œ μŠ€μœ„ν”„νŠΈμ˜ ν•¨μˆ˜λŠ” 일급객체이닀. κ·Έλž˜μ„œ ν•¨μˆ˜λ₯Ό λ³€μˆ˜, μƒμˆ˜ 등에 할당이 κ°€λŠ₯ν•˜κ³  λ§€κ°œλ³€μˆ˜λ₯Ό 톡해 전달할 μˆ˜λ„ μžˆλ‹€.
  • ν•¨μˆ˜μ˜ νƒ€μž… ν‘œν˜„ : λ°˜ν™˜ νƒ€μž…μ„ μƒλž΅ν•  수 μ—†λ‹€.
var someFunction: (String, String) -> Void = greeting(to:from:)
someFunction("eric", "kdgt") // Hello eric! I'm kdgt

someFunction = greeting(friend:me:)
someFunction("eric", "kdgt") // Hello eric! I'm kdgt


// νƒ€μž…μ΄ λ‹€λ₯Έ ν•¨μˆ˜λŠ” ν• λ‹Ήν•  수 μ—†λ‹€ - 컴파일 였λ₯˜ λ°œμƒ
//someFunction = sayHelloToFriends(me: friends:)


func runAnother(function: (String, String) -> Void) {
    function("jenny", "mike")
}

// Hello jenny! I'm mike
runAnother(function: greeting(friend:me:))

// Hello jenny! I'm mike
runAnother(function: someFunction)

 

Tip : ν•¨μˆ˜λ„ λ³€μˆ˜λ‘œ 할당이 κ°€λŠ₯ν•˜λ‹€! Swiftμ—μ„œλŠ” 띄어쓰기가 μ€‘μš”ν•˜λ‹€.