iOS
Swift: A Swift Tour - Functions and Closures
Dev Arthur
2023. 4. 25. 00:58
<Funtions and Closures>
- Use func to declare a function.
= 함수를 선언하기 위해 'func'을 사용한다 - Call a function by following its name with a list of arguments in parentheses.
= 함수의 이름과 괄호 안의 인수 목록을 통해 함수를 호출한다
※인수(Argument)와 인자(매개변수, Parameter)의 차이
인수: 함수를 호출할 때, 사용되는 값
인자: 함수를 정의할 때, 사용되는 값 - Use -> to separate the parameter names and types from the function’s return type.
= '->'를 사용해서 '매개변수의 이름과 타입'과 '함수의 리턴 타입'을 분리한다 - ex)
func hello(name: String, age: Int) -> String{
return "Hello, my name is \(name), \(age) year old"
}
print(hello(name: "Arthur", age: 26))
// Hello, my name is Arthur, 26 year old
- By default, functions use their parameter names as labels for their arguments.
= 기본적으로 함수는 함수의 매개변수 이름을 함수의 인수 레이블로 쓴다 - Write a custom argument label before the parameter name, or write _ to use no argument label.
= 매개변수 이름 앞에 '사용자 정의 인수 레이블'을 쓰거나, '_'(언더바)를 써서 인수 레이블을 안 쓸 수도 있다 - ex)
func hello(_ name: String, old age: Int) -> String{
return "Hello, my name is \(name), \(age) year old"
}
print(hello("Arthur", old: 26))
// Hello, my name is Arthur, 26 year old
- Use a tuple to make a compound value.
= 튜플을 이용해서 복합 값을 만들 수 있다 - The elements of a tuple can be referred to either by name or by number.
= 튜플의 요소는 이름이나 번호로 참조될 수 있다 - ex)
func mydata(_ age: Int, hi height: Int, we weight: Int) -> (age: String, height: String, weight: String){
return (String(age),String(height),String(weight))
}
let data = mydata(26, hi: 177, we: 60)
print(data.1)
// 177
print(data.weight)
// 60
// 만약 반환 값에 이름 레이블을 주지 않는다면, 번호로만 값을 참조할 수 있다
// ex) (String, String, String)
- Functions can be nested.
= 함수는 중첩될 수 있다 - Nested functions have access to variables that were declared in the outer function.
= 중첩 함수는 외부 함수에서 선언된 변수들에 접근할 수 있다 - You can use nested functions to organize the code in a function that’s long or complex.
= 중첩 함수를 사용해서 길거나 복잡한 함수의 코드를 구성할 수 있다 - ex)
func outFunc() -> Int{
var a = 10
func inFunc(){ //함수는 중첩될 수 있다
a += 5 //외부 함수에서 선언된 변수들에 접근할 수 있다
}
inFunc()
return a
}
print(outFunc())
// 15
- Functions are a first-class type.
= 함수는 일급 클래스 타입이다(※일명 일급 함수) - This means that a function can return another function as its value.
= 일급 함수는 또다른 함수를 함수의 리턴 값으로 사용할 수 있는 함수를 말한다 - ex)
func firstclassFunc() -> ((Int) -> Int){
func valueFunc(number: Int) -> Int{
return number + 5
}
return valueFunc //또다른 함수를 리턴값으로 사용할 수 있다
}
var numberFunc = firstclassFunc()
print(numberFunc(10))
// 15
- A function can take another function as one of its arguments.
= 일급 함수는 함수의 인수 중 하나를 또다른 함수로 사용할 수 있다 - ex)
func firstclassFunc(_ number: Int, _ IsOdd: (Int) -> Bool) -> Int{
if IsOdd(number){
return number + 1
}
return number
}
func argumentFunc(number: Int) -> Bool{
return number%2 != 0
}
print(firstclassFunc(9, argumentFunc) //또다른 함수를 인수 중 하나로 사용할 수 있다
// 10
- Functions are actually a special case of closures: blocks of code that can be called later.
= 함수는 실제로 클로저의 특수한 케이스다: 나중에 호출할 수 있는 코드 블록(=클로저) - The code in a closure has access to things like variables and functions that were available in the scope where the closure was created,
= 클로저의 코드는 '클로저가 생성된 범위에서 사용 가능한 변수나 함수'와 같은 것에 접근 가능하다 - even if the closure is in a different scope when it’s executed — you saw an example of this already with nested functions.
= 심지어, 클로저가 실행될 때 다른 범위에 있어도 접근 가능하다(중첩 함수가 그 예시이다) - You can write a closure without a name by surrounding code with braces ({}).
= 코드를 중괄호로 둘러싸서 클로저를 이름 없이 작성할 수 있다 - Use 'in' to separate the arguments and return type from the body.
= 'in'을 사용해서 인수와 리턴 타입을 바디에서 분리할 수 있다 - ex)
let numbers = [1,2,3,4,5]
let numbersNew = numbers.map({ (number: Int) -> Int in
if (number % 2 != 0){
return 0
}
else{
return number
}
})
print(numberNew)
// [0,2,0,4,0]
- When a closure’s type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both.
= 델리게이트 콜백과 같이 클로저의 타입을 이미 알고있는 경우, 인자의 타입이나 리턴 타입 혹은 둘 다를 생략할 수 있다 - Single statement closures implicitly return the value of their only statement. (?)
= 단일 구문인 클로저는 암시적으로 그 구문의 값을 반환한다 - ex)
let numbers = [1,2,3,4,5]
let numbersNew = numbers.map({ number in 10 * number})
print(numbersNew)
// [10,20,30,40,50]
- You can refer to parameters by number instead of by name — this approach is especially useful in very short closures.
= 이름 대신 숫자를 사용해서 인자를 참조할 수 있다(매우 짧은 클로저를 만드는데 유용하다) - A closure passed as the last argument to a function can appear immediately after the parentheses.
= 함수의 마지막 인수로 전달된 클로저는 괄호 뒤에 바로 나타날 수 있다 - When a closure is the only argument to a function, you can omit the parentheses entirely.
= 클로저가 함수의 유일한 인자일 경우, 괄호 전체를 생략할 수 있다 - ex)
let numbers = [1,2,3,4,5]
let numbersNew = numbers.sorted { $0 > $1 }
print(numbersNew)
// [5,4,3,2,1]
반응형