본문 바로가기
 IOS,Swift/Swift⌘

Swift - Function 1

by 시에라177 2022. 6. 25.

#0 스위프트에서 함수는 타입을 가지고 있다.

파이썬이나 c언어를 생각해보면 처음에 이 말이 잘 와닿지 않는다. 함수가 타입을 가지고 있다니.

Swift.org에서는 다음과 같이 말한다.

Every function in Swift has a type, consisting of the function’s parameter types and return type.

->즉, "(파라미터1의 타입, 파라미터2의 타입) -> 반환값의 타입"이 함수의 타입이라는 것. 57이라는 정수의 타입이 "Int"인 것처럼.

* 반환형이 없더라도 함수의 타입은 -> Void를 포함해주어야한다.

func charStr(imo: Character) -> String{
   return "\(imo)\(imo)\(imo)\(imo)\(imo)"
}

예시로 위의 함수의 타입은 "(Character) -> String"이다. 

 

#1 함수의 파라미터로서 함수, 함수의 반환값으로서 함수.

You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions. 

Function Types as Parameter Types. You can use a function type such as (Int, Int) -> Int as a parameter type for another function

Function Types as Return Types .You can use a function type as the return type of another function.

"이러한 함수의 타입을 다른 모든 타입들과 마찬가지로 스위프트에서 사용할 수 있다. 그리고 이것은 함수를 파라미터로서 다른 함수에에 넘길 수도 있게 해주며, 그리고 함수를 함수의 반환값으로 할 수도 있다."

ex) 함수에 함수를 대입. var, let도 사용함에 주의.

var charStrCopied: (Character) -> String = charStr(imo:)
print(charStrCopied("⌘"))

ex)greet(person:alreadyGreeted:)

ex) argument로 함수를 넘기는 예  파라미터명:_argument로 사용될 함수(매개변수명:전달인자레이블:)

helloWithChar(from: "Sierra", to: "Blue", "Black", "Red", imo: "😵‍💫", charFunc: charStr(imo:))

 

 

#2 함수의 이름, 함수를 Call(호출)할때.

⌘To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function’s parameters.

-함수를 호출할 땐 이름과 함께 파라미터의 순서와 파라미터의 타입에 맞게 argument를 넘겨주어야 한다. 그리고 전달인자레이블을 사용하는 경우에, 함수의 call에선 전달인자레이블을, 함수의 구현에선 파라미터의 Name을 사용한다.

ex)아래 코드에서 함수 구현할 때는 파라미터명을 쓰고 있으며, 밑의 함수Call에서는 전달인자레이블을 사용한다.

func helloWithChar(from me: String, to friends: String..., imo: Character, charFunc: (Character) -> String) -> Void{
    print("Hello \(friends) \t i'm \(me). \t \(charFunc(imo))")
}

helloWithChar(from: "Sierra", to: "Blue", "Black", "Red", imo: "😵‍💫", charFunc: charStr(imo:))

 

' IOS,Swift > Swift⌘' 카테고리의 다른 글

Swift - Optional  (0) 2022.07.01
Swift - Enumeration  (0) 2022.06.30
Swift - Collection Type1 Array  (0) 2022.06.28
Swift - Declaring Constants(let) & Variables(var)  (0) 2022.06.26
Swift - String & Characters  (0) 2022.06.25