πŸ‘©πŸ»‍πŸ’»/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)