iOS 5강 Function and Optional

린다·2021년 1월 23일
0

iOS beginner

목록 보기
4/14
post-thumbnail

Function


함수 실습 (1)

[ ex 1 ]

func printName(){
    print("---> 이름: 린다")
}
// 함수 생성
printName()
// 함수 작동

[ ex 2 ] input을 받는 경우

func printMultipleofTen (value: Int) {
    print("\(value) * 10 = \(value * 10)")
}
printMultipleofTen(value:5)

[ ex 3 ]

func printTotalprice (price: Int, count: Int){
    print("Total price: \(price * count) ")
}
printTotalprice(price:1500, count:5)

파라미터 이름 변경

func printTotalprice (_ price: Int, _ count: Int){
    print("Total price: \(price * count) ")
}
printTotalprice(1500, 5)
func printTotalprice (가격 price: Int, 갯수 count: Int){
    print("Total price: \(price * count) ")
}
printTotalprice(가격: 1500, 갯수: 5)

변수 앞에 적힌 부분이 외부에 보이는 모습


함수 실습 (2)

함수에 디폴트 값을 설정할 수 있음

func printTotalpricewithDefault (price: Int = 1500, count: Int){
    print("Total price: \(price * count) ")
}
printTotalpricewithDefault(count: 5)
//default 값이 설정된 상태에서 생략한 채 사용한다면 default 값이 적용됨

--> 이때 Total price 값을 사용하고 싶으면 값을 반환받아야함

func totalPrice (price: Int, count: Int) -> Int {
    let totalPrice = price * count
    return totalPrice
}
let price = totalPrice(price: 10000, count: 77)
// ->Int : return 키워드, 무언가를 결과로 반환할 때 사용

고급 기능 (1)

✨ 소수점까지 사용할 경우에는 Double 사용
✨ 오버로드: 같은 이름, 다른 행동

func totalPrice(price: Int, count: Int){
    print("Total price: \(price * count) ")
}

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

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

✨In-out parameter : 받은 값을 바꾸고 싶을 때

func incrementAndPrint(_ value: Int){
    value += 1 //constant를 바꾸려고해서 오류남
    print(value)
}

-> 변수 앞에 inout을 작성해주고 함수를 작동시킬 때도 변수 앞에 &을 붙여줘야 작동

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

고급 기능 (2)

✨ 함수를 인자로 사용하는 법

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 add(_ a: Int, _ b: Int) -> Int {
    return a+b
}

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

func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    let result = function(a,b)
    print(result)
}
// a,b를 function에 넘기면 그 result를 프린트해주는 함수

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

Optional

optional 기초

var name: String = "Joon"
var dogName: String = "Mozzi"
var carName: String = ???

optional: 어떤 값을 갖고 있지 않은 경우 / 갖고 있는 경우 모두 표현할 수 있게 해줌

  • 없다는 표시: nil

optional 기초 실습

var carName: String?
carName = nil //이름이 없는 상태 표현
carName = "땡크" //데이터를 할당
let num = Int("10") //성공
let num = Int("10하이") //실패

optional 고급 (1)

optional의 고급 기능 4가지
1) Forced unwrapping : 억지로 박스를 까보자
2) Optional binding 1 (if let) : 부드럽게 박스를 까보자
3) Optional binding 2 (guard) : 부드럽게 박스를 까보자 2
4) Nil coalescing : 박스를 까봤더니 값이 없으면 디폴트 값을 줘보자

1. Forced unwrapping

var carName: String?
carName = "땡크"

print(carName) //Optional("땡크")
print(carName!) //박스를 까서 value만 가져오는 행위: 땡크

carName = nil
print(carName!) //오류남

2. Optional binding "if let"

if let unwrappedCarName = carName {
    print(unwrappedCarName)
} else{
    print("carName 없다")
}
//변수에 값이 할당돼있는 경우에는 값을 프린트, nil인 경우에는 다른 값 프린트하도록 설정
func printParsedInt(from: String){
    if let parsedInt = Int(from) {
        print(parsedInt)
    } else {
        print("Int로 변환안됨")
    }
}

printParsedInt(from: "100") //100
printParsedInt(from: "헬로우") //Int로 변환안됨

3. Optional binding "guard"

func printParsedInt(from: String){
    guard let parsedInt = Int(from) else{ //이 구문 통과하면 빠져나가서 print(parsedInt)로. 만약 통과하지 못하면 괄호 안 내용 수행하고 함수 빠져나감
        print("Int로 변환안됨")
        return
    }
    print(parsedInt)
}

4.Nil coalescing

let myCarName: String = carName ?? "모델S"
//carName이 nil 일 경우, 뒤에 있는 "모델S"를 default로 넣어줘

0개의 댓글

관련 채용 정보