[10/23] Function and Optional

Dino·2022년 10월 23일
0

패스트캠퍼스

목록 보기
4/4

Function and Optional

Function

함수는 어떤 기능을 수행하는 코드 블럭

  • function의 기본 형태
func functionName(exteranlName param: ParamType) -> ReturnType {
    //....
    return returnValue
}
  • function 사용 예
func printName() {
    print("My name is Jon")
}
printName() // My name is Jon
  • 숫자를 받아서 10을 곱해서 출력한다
func printMultipleOfTen(value: Int) {
    print("\(value) * 10 = \(value * 10)")
}

printMultipleOfTen(value: 3)
  • 물건값과 갯수를 받아 전체 금액을 출하는 함수
func printTotalPrice(price: Int, count: Int) {
    print("Total Price: \(price * count)")
}

printTotalPrice(price: 3500, count: 3)

func printTotalPrice(가격 price: Int, 갯수 count: Int) {
    print("Total Price: \(price * count)")
}

printTotalPrice(가격: 3500, 갯수: 3)

func printTotalPriceWuthDefaultValue(price: Int = 1500, count: Int) {
    print("Total Price: \(price * count)")
}

printTotalPriceWuthDefaultValue(count: 3)
printTotalPriceWuthDefaultValue(count: 10)
printTotalPriceWuthDefaultValue(count: 32)

printTotalPriceWuthDefaultValue(price: 3500, count: 1)


func totalPrice(price: Int, count: Int) -> Int {
    let totalPrice = price * count
    return totalPrice
}

let calculatedPrice = totalPrice(price: 10000, count: 7)
calculatedPrice

도전과제
1. 성, 이름을 받아서 fullname을 출력하는 함수 만들기
2. 1번에서 만든 함수를 파라미터 이름을 제거하고 fullname을 출력하는 함수 만들기
3. 성, 이름을 받아서 fullname return 하는 함수 만들기

  • 1번
func printFullName (fristName: String, lastName: String) {
    print("제 이름은 \(fristName)\(lastName)입니다")
}
printFullName(fristName: "park", lastName: "tae")
  • 2번
func printFullName (_ fristName: String, _ lastName: String) {
    print("제 이름은 \(fristName)\(lastName)입니다")
}
printFullName("park", "tae")
  • 3번
func fullName (fristName: String, lastName: String) -> String {
    return "\(fristName) \(lastName)"
}
let name = fullName(fristName: "park", lastName: "tae")
name

overloading

  • 같은 함수의 이름을 가지고 있지만 파라미터를 다르게 하여 다양한 유형의 호출에 응답이 가능한 것. 같은 이름, 다른 행동
func printTotalPrice(price: Int, count: Int) {
    print("Total Price: \(price * count)")
}

func printTotalPrice(price: Double, count: Double) {
    print("Total Price: \(price * count)")
}

func printTotalPrice(가격: Int, 개수: Int) {
    print("Total Price: \(가격 * 개수)")
}

In-out parameter
Swift에서 함수의 파라미터는 상수(Constant)이므로 함수 내부에서 파라미터의 값을 변경할 수 없다 만약 함수의 파라미터 값을 변경하고, 변경된 값이 함수 호출이 종료된 후에도 지속되길 원하ㄷ면 inout 파라미터를 사용하면 된다.

var value = 3
func incrementAndPrint(_ value: inout Int) {
    value += 1
    print(value)
}

incrementAndPrint(&value)

function as a parameter

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

func subtract(_ a: Int, _ b: Int) -> Int {
    return a - b
}

var function = add
function(4, 2)
function = subtract
function(4, 2)

func printResult(_ function:(Int, Int) -> Int, _ a: Int, _ b: Int) {
    let result = function(a, b)
    print(result)
}

printResult(add, 10, 5)
printResult(subtract, 10, 5)

Optional

변수에 값이 들어갈 수도 있고, 아닐 수도 있다 (nil)

  • optional 변수 생성
var carName: String?
var bikeName: String!
  • 영화배우의 이름을 담는 변수를 작성 (타입 String?)
var favoriteMovieStar: String?
favoriteMovieStar = "송강호"

Optional 고급 기능 4가지

  • Nil coalescing
    • 박스를 까봤더니, 값이 없으면 디폴트 값을 줘보자
  • Forcd unwrapping
    • 억지로 박스를 까보기
var carName: String? = "아우디"
print(carName!)
  • Optional binding (if let)
    • 부드럽게 박스를 까보기 1
carName = nil

if let unwrappedCarName = carName {
    print(unwrappedCarName)
} else {
    print("Car Name이 없다")
}

func printParsedInt(from: String) {
    if let parsedInt = Int(from) {
        print(parsedInt)
    } else {
        print("Int로 컨버팅 안됩니다")
    }
}

printParsedInt(from: "100") // 100
printParsedInt(from: "Hello") // Int로 컨버팅 안됩니다
  • Optional binding (guard)
    • 부드럽게 박스를 까보기 2
func printParsedInt(from: String) {
    guard let parsedInt = Int(from) else {
        print("Int로 컨버팅 안됩니다 ")
        return
    }
    
    print(parsedInt)
}

//printParsedInt(from: "100")
printParsedInt(from: "Hello")
  • Nil coalescing
    • 박스를 까봤더니, 값이 없으면 디폴트 값을 줘보자
carName = "모델 3"
let myCarName: String = carName ?? "모델 S"

도전과제
1. 최애 음식이름을 담는 변수를 작성하시고 (String?)
2. 옵셔널 바인딩을 이용해서 값을 확인해보기
3. 닉네임을 받아서 출력하는 함수 만들기, 조건 입력 파라미터는 String?

  • 1번
let favoriteFood: String? = "소고기"
  • 2번
if let foodName = favoriteFood {
    print(foodName)
} else {
    print("좋아하는 음식 없음")
}
  • 3번
func printNickNmae(name: String?) {
    guard let printNickNmae = name else {
        print("닉네임을 만들어보자")
        return
    }
    print(printNickNmae)
}

printNickNmae(name: "Dino")

참고 : FastCampus iOS 앱 개발 올인원 패키지

profile
깃허브 : https://github.com/Hangga99

0개의 댓글