본문 바로가기
FE 공부/Swift

Swift _ Functions

by 꼬질꼬질두부 2022. 10. 3.
반응형
특정 기능을 수행하는 코드 조각

 

장점
Reusability _  불필요한 코드 반복을 방지


특징
- 코드 내에서 함수 표기 시에는 괄호를 빼거나 argument label만 표기
//예제1
func printHello(with name: String) {
	print("hello, \(name)")
}

let f2: (String) -> ( ) = printHello(with:)
let f3 = printHello(with:)
f3("World") // hello, World

//예제2
func add(a: Int, b: Int) -> Int{
	return a + b
}

var f4: (Int, Int) -> Int = add(a:b:)

f4(1, 2) // 3

- first class citizen
  • 변수와 상수에 저장할 수 있음
  • parameter로 전달할 수 있음
  • 함수와 메소드에서 리턴할 수 있음

 

 

Calling Function : 함수 호출

functionaName(parameters)

// 예제
print("hello")

 

 

Defining Function : 함수 선언

func name(parameters) -> ReturnType {
	statements
}

//예제

func sayHello{
print("hello")
}

sayHello() //"hello\n"

 

return 이란?

 

- 함수의 실행을 중단시킴

- 함수에 return 값이 있다면 그 다음에 오는 식을 평가한 후 return 값을 호출한 곳으로 전달해줌

func name(parameters) -> ReturnType {
	statements
	return expression
}

//예제
func add() -> Int{
	return 1 + 7
}

let r = add() //return 값은 함수가 호출되는 곳으로 전달됨

 

단일 표현식이라면  컴파일러의 추론이 가능하기 때문에 return을 안적어도 됨  _ "Implicit Return"

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

add(a: 1,b: 2)

 

 

parameter 란?

>> 함수에 전달하는 값

//parameter는 함수 안에서 사용되는 임시 상수

func name(parameters) -> ReturnType {
	statements
	return expression
}

//parameter가 2개 이상일 경우
(name: Type, name: Type)
//예제
func add(a: Int, b: Int) -> Int{
	return a + b
}

//Calling Functions _ 함수 호출 시
functionName(parameterName: expression)

(name: Type = Value) //parameter 기본값 지정 가능
//예제
func sayHello(to: String = "DuBu"){
print("Hello, \(to)")
}

sayHello(to: "Swift") //Hello, Swift
sayHello() //Hello, DuBu

 

 

Nested Functions _ 중첩 함수

//예제

func outer() -> () -> () {
	func inner() { //Nested function _ 호출할 수 있는 범위가 outer 내부
		print("inner")
    }
    print("outer")
    return inner
}

let f = outer()
f()

 

반응형

'FE 공부 > Swift' 카테고리의 다른 글

Swift_Structure & Class  (0) 2022.10.10
Swift _ Collection  (2) 2022.10.04
Swift _ Tuples, Strings and Characters  (0) 2022.10.04
Swift _ Closures  (2) 2022.10.04
Swift _ Optional  (0) 2022.10.03

댓글