Day 5 : 함수

sun·2021년 9월 15일
0

100 Days of SwiftUI

목록 보기
2/11

[Day 5]

@ Day 5

# 매개변수

  • 함수 작성 시 매개변수의 이름과 타입을 반드시 써줘야 함
func square(number: Int) {
	print(number * number)
}

square(number: 8)

매개변수 이름

  • 함수 호출 시함수 내부에서의 매개변수의 이름을 다르게 지정할 수 있음
func sayHello(to name: String) {
	print("Hello, \(name)!")
}

sayHello(to: "Taylor")

매개변수 이름이 생략 가능한 경우

  • 함수 호출 시의 매개변수의 이름을 _으로 지정하면 호출 시 매개변수 이름을 생략할 수 있음
  • 주로 함수 이름이 동사이고, 호출 시 매개변수를 생략하는 게 더 자연스러울 때 사용
func greet(_ person: String) {
	print("Hello, \(person)!")
}

greet("Taylor Swift")

디폴트 매개변수

  • 매개변수의 타입 다음에 = 을 이용해서 디폴트값 지정
func greet(_ person: String, nicely: Bool = true) {
    if nicely == true {
        print("Hello, \(person)!")
    } else {
        print("Oh no, it's \(person) again...")
    }
}

greet("Taylor")
greet("Taylor", nicely: false)

# 리턴 값

  • 리턴 값의 타입을 지정해줘야 함
func square(number: Int) -> Int {
	return number * number
}

let result = square(number: 8)
  • 복수의 값을 리턴해야 한다면 튜플 이용

리턴 값이 생략 가능한 경우

  • 함수 내부에 오직 하나의 표현식만 존재하는 경우 return 키워드 생략 가능
  • 반복문, 조건문, 변수 선언 등의 구문이 존재하면 생략 불가하나 삼항 연산자는 생략 가능
func doAdd() -> Int {
	5 + 5
}

print(doAdd())  // 10


func greet(name: String) -> String {
	name == "Taylor Swift" ? "Oh wow!" : "Hello \(name)!"
}

print(greet("Taylor Swift"))  // "Oh wow!"

# 가변 매개변수(Variadic) 함수

  • 매개변수의 타입 뒤에 ... 를 쓰면 가변 매개변수가 됨
  • 호출 시에 , 로 구분해서 인자를 보내면 함수 내부적으로는 배열로 받아들여 처리
  • 인자에 아무것도 넣지 않고 호출하기도 가능
func square(numbers: Int...) {
	for number in numbers {
   		print(number * number)
    }
}

square(numbers: 1, 2, 3, 4, 5)

# 에러 처리

  • 함수 정의 시에 throws 키워드를 통해 특정 에러 발생 시에 해당 에러를 던지도록 할 수 있음
  • do-try-catch 를 이용해서 에러 처리 : 에러 발생 시 바로 catch 블록으로 이동
enum PasswordError: Error {
	case obvious
}

func checkPassword(_ password: String) throws -> Bool {
	if password == "password" {
    		throw PasswordError.obvious
    }
    
    return true
}

do {
	try checkPassword(//some type of password)
    	print("That password is good!")
} catch {
	print("You can't use that password.")
}

# inout 매개변수

  • 스위프트의 포인터 개념으로 인자 앞에 &을 붙여서 사용
func doubleInPlace(number: inout Int) {
	number *= 2
}

var myNum = 10
doubleInPlace(number: &myNum)
print(myNum)  //20
profile
☀️

0개의 댓글