Function / Optional

Swift/문법 2021. 2. 26. 21:48

Function

import UIKit

func printName() {
    print("My name is khon")
}
printName()
print("\n")


func multipleOfTen(value: Int) {
    print("\(value) * 10 = \(value * 10)")
}
multipleOfTen(value: 10)
print("\n")


func TotalPrice(price: Int, count: Int) {
    print("Total Price: \(price * count)")
}
TotalPrice(price: 1550, count: 10)
print("\n")

// _ 사용하면 파라미터 이름을 쓰지 않고 값을 입력 할 수 있음
func TotalPrice2(_ price: Int, _ count: Int) {
    print("Total Price2: \(price * count)")
}
TotalPrice2(5, 10)
print("\n")

// 한글도 사용할수 있음
func TotalPrice3(가격 price: Int, 개수 count: Int) {
    print("총 가격: \(price * count)")
}
TotalPrice3(가격: 6000, 개수: 5)
print("\n")

// price 값을 1500으로 고정
func TotalPrice4(price: Int = 1500, count: Int) {
    print("Total Price4: \(price * count)")
}

TotalPrice4(count: 10)

// 고정된 값을 변경해서 사용할수 있음
TotalPrice4(price: 2000, count: 20)


// Int형으로 return
func TotalPrice5(price: Int, count: Int) -> Int {
    let TotalPrice5 = price * count
    return TotalPrice5
}
let calculatedPrice = TotalPrice5(price: 20000, count: 16)
calculatedPrice


// 성, 이름을 받아서 Fullname을 출력하는 함수
func fullName1(firstName: String, lastName: String) {
    print("\(firstName) \(lastName)")
}
fullName1(firstName: "k1", lastName: "hon")



// 함수의 파라미터 이름을 제거하고 fullname 출력하는 함수
func fullName2(_ firstName: String, _ lastName: String) {
    print("\(firstName) \(lastName)")
}
fullName2("k2", "hon")



// 성, 이름을 받아서 fullname return 하는 함수
func fullName3(firstName: String, lastName: String) -> String {
    return "\(firstName) \(lastName)"
}
let printFullName = fullName3(firstName: "k3", lastName: "hon")
print("\(printFullName)")



// 오버로드
// 함수 이름이 같지만 안에 타입이나 내용이 다를 때
func TotalPrice(price: Int, count: Int) {
    print("Total Price: \(price * count)")
}
TotalPrice(price: 5, count: 5)

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


// In / out
// 파라미터 안에 있는 값은 constant 값이라 변경이 불가능 그래서 값을 변경하고 싶을때는 inout을 사용
var value = 50
func inoutFunc(_ value: inout Int) {
    value += 1
    print("\(value)")
}
inoutFunc(&value)


// 파라미터 값을 넘기기
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

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

var function = add
function(5, 3)
function = subtract
function(10, 3)

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

 

 

 

옵셔널

옵셔널 종류

1. Forced Unwrapping

- !

 

2. Optional Binding (If let / guard)

- if let은 Cyclomatic Complexity가 올라갈 수 있음

 

3. Nil coalescing

 

import UIKit

// ? 있을수도 있고 없을수도 있다 라는 뜻
var carName: String?
carName = "Tesla"

let num = Int("10")


// Forced Unwrapping
print(carName!)


// if let
if let unwrappedCarName = carName {
    print(unwrappedCarName)
} else {
    print("No Value")
}


func parsedInt(from: String) {
    if let parsedInt = Int(from) {
        print(parsedInt)
    } else {
        print("컨버팅 불가\n")
    }
}
//parsedInt(from: "100\n")
//parsedInt(from: "hello\n")


// guard
func parsedIntGuard(from: String) {
    guard let parsedIntGuard = Int(from) else {
        print("컨버팅 불가")
        return
    }
    print(parsedIntGuard)
}
parsedIntGuard(from: "1000")
//parsedIntGuard(from: "Hello")



// nil coalescing
// carName이 nil이라면 S Class를 default 값으로 넘겨줌
carName = "BMW"
let myCarName: String = carName ?? "S Class"
print("\n")



// 좋아하는 음식 이름을 담는 변수 작성 (String?)
let favoriteFood: String? = "Apple"



// 옵셔널 바인딩으로 값 확인
if let unwrappedFavoriteFood = favoriteFood {
    print(unwrappedFavoriteFood)
} else {
    print("No")
}



// 닉넴임을 받아서 출력 함수 만들기, 입력 파라미터는 String?
func nickName(name: String?) {
    guard let nickname = name else {
        print("닉네임 없음")
        return
    }
    print(nickname)
}
nickName(name: "khon")

'Swift > 문법' 카테고리의 다른 글

Structure / Protocol  (0) 2021.03.02
Array / Dictionary / Set  (0) 2021.03.01
While / if / Repeat / for / Switch  (0) 2021.02.26
Tuple / Bool / Scope  (0) 2021.02.25
고차 함수(higher order function)  (0) 2021.01.30
Posted by khon98
,