swift unwrap + 옵셔널 변수, ??

joo lee·2022년 6월 28일
0


으릅당...

unwrap 이해하기

import UIKit

//옵셔널이란?
//값이 있을 수도 있고, 없을 수도 있다.

var someVariable : Int? = nil

if someVariable == nil {
    someVariable = 90
}

print("someVariable ", someVariable)

//언래핑이란? 랩 즉 감싸져 있는 것을 벗기는 것 someVariable 의 변수를 otherVariable의 이름으로 넣어서 옵셔널을 () 벗긴다.

if let otherVariable = someVariable {
    print("언래핑 되었다. 즉 값이 있다. otherVariable : \(otherVariable)")
} else {
    print("값이 없다.")
}

var firstValue : Int? = 30
var secondValue : Int? = 50

print("firstValue: \(firstValue)")
print("secondValue: \(secondValue)")

unwrap(parameter: firstValue)
unwrap(parameter: secondValue)

someVariable = nil

// let myValue = someVariable ?? 10 : ?? : someVariable 이 비어있으면 즉 값이 없으면 기본값으로 요놈을 넣겠다.

let myValue = someVariable ?? 10
print("myValue: \(myValue)")

func unwrap(parameter: Int?) {
    print("unwrap() called")
    //값이 없으면 리턴 해버린다.
    //파라메터 : 메소드안에 넣는 재료
    guard let unWrappedParam = parameter else {
        return
    }
    print("unWrappednParam: \(unWrappedParam)")
}

// 옵셔널 벗기기 : 언래핑
// 언래핑 하는 법 : if let 으로 벗기거나,
// guard let으로 벗긴다.

결과값

someVariable Optional(90)
언래핑 되었다. 즉 값이 있다. otherVariable : 90
firstValue: Optional(30)
secondValue: Optional(50)
unwrap() called
unWrappednParam: 30
unwrap() called
unWrappednParam: 50
myValue: 10


??

A ?? B
A가 null 일때, B로
https://supercoding.tistory.com/12


사실, 옵셔널? 쓰라고 해서 쓰고,
언래핑하래서 했다.

아직 사용해보지 않아서 왜 쓰는지 모르겠다.
좀 더 고민해봐야겠다.

profile
와플좋아하고 개발공부하는 디자이너 리입니다.

0개의 댓글