๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป/Swift

6. ํ•จ์ˆ˜ ๊ธฐ๋ณธ, ๊ณ ๊ธ‰ - iOS ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ์œ„ํ•œ ์Šค์œ„ํ”„ํŠธ ๊ธฐ์ดˆ

reujusong 2020. 6. 16. 16:16
import Swift

func sum(a: Int, b: Int) -> Int {
    return a + b
}

//๋ฐ˜ํ™˜๊ฐ’์ด ์—†๋Š” ํ•จ์ˆ˜
func printMyName(name: String) -> Void {
    print(name)
}

//Void ๋Š” ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
func printYourName(name: String) {
    print(name)
}


//๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์—†๋Š” ํ•จ์ˆ˜
func maximumIntegerValue() -> Int {
    return Int.max
}

//MARK: - ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’
// ๊ธฐ๋ณธ๊ฐ’์„ ๊ฐ–๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ชฉ๋ก ์ค‘์— ๋’ค์ชฝ์— ์œ„์น˜ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค
func greeting(friend: String, me: String = "kdgt") {
    print("Hello \(friend)! I'm \(me)")
}

// ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’์„ ๊ฐ€์ง€๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ƒ๋žตํ•  ์ˆ˜ ์žˆ๋‹ค
greeting(friend: "hana") // Hello hana! I'm kdgt
greeting(friend: "john", me: "eric") // Hello john! I'm eric

//MARK: - ์ „๋‹ฌ์ธ์ž ๋ ˆ์ด๋ธ”
// ์ „๋‹ฌ์ธ์ž ๋ ˆ์ด๋ธ”์€ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ 
// ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ์—ญํ• ์„ ์ข€ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ํ•˜๊ฑฐ๋‚˜ 
// ํ•จ์ˆ˜ ์‚ฌ์šฉ์ž์˜ ์ž…์žฅ์—์„œ ํ‘œํ˜„ํ•˜๊ณ ์ž ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค
// ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์ „๋‹ฌ์ธ์ž๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ์—๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜ ์ด๋ฆ„์„ ์‚ฌ์šฉํ•œ๋‹ค
func greeting(to friend: String, from me: String) {
    print("Hello \(friend)! I'm \(me)")
}

// ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ์—๋Š” ์ „๋‹ฌ์ธ์ž ๋ ˆ์ด๋ธ”์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค
greeting(to: "hana", from: "kdgt") // Hello hana! I'm kdgt

//MARK: - ๊ฐ€๋ณ€ ๋งค๊ฐœ๋ณ€์ˆ˜
// ์ „๋‹ฌ ๋ฐ›์„ ๊ฐ’์˜ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๊ธฐ ์–ด๋ ค์šธ ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
// ๊ฐ€๋ณ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ํ•จ์ˆ˜๋‹น ํ•˜๋‚˜๋งŒ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
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!

 

๋‹ค๋ฅธ ์–ธ์–ด์™€ ๋‹ค๋ฅธ ์ ๋„ ์žˆ๋‹ค.

 

- ๋ฐ์ดํ„ฐ ํƒ€์ž…์œผ๋กœ์„œ์˜ ํ•จ์ˆ˜

์Šค์œ„ํ”„ํŠธ๋Š” ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํŒจ๋Ÿฌ๋‹ค์ž„์„ ํฌํ•จํ•˜๋Š” ๋‹ค์ค‘ ํŒจ๋Ÿฌ๋‹ค์ž„ ์–ธ์–ด์ด๋‹ค. ์Šค์œ„ํ”„ํŠธ์˜ ํ•จ์ˆ˜๋Š” ์ผ๊ธ‰๊ฐ์ฒด์ด๋ฏ€๋กœ ๋ณ€์ˆ˜, ์ƒ์ˆ˜ ๋“ฑ์— ์ €์žฅ์ด ๊ฐ€๋Šฅํ•˜๊ณ  ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ํ†ตํ•ด ์ „๋‹ฌํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

 

//MARK: ํ•จ์ˆ˜์˜ ํƒ€์ž…ํ‘œํ˜„
// ๋ฐ˜ํ™˜ํƒ€์ž…์„ ์ƒ๋žตํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค
// (<#๋งค๊ฐœ๋ณ€์ˆ˜1ํƒ€์ž…#>, <#๋งค๊ฐœ๋ณ€์ˆ˜2ํƒ€์ž…#> ...) -> <#๋ฐ˜ํ™˜ํƒ€์ž…#>

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)