스위프트 Optional

iOS and Swift Terminology - Optional

Sources from developer.apple.com

A type that represents either a wrapped value or nil, the absence of a value

Optional?

😱 optional도 enum이다.

let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
let x: String? = ...
if let y = x { //do something with y }
swithch x {
	case .some(let y): // do something with y
	case .none: break 
}

nil

Unwrap

🤡 Forced Unwrapping : 강제 해제

func testFuc(optionalStr:String?){
	if optionalStr != nil { // 크래쉬 방지
		let unwrapStr:String = optionalStr! 
		print(unwrapStr)
	}
}

🤡 Optional Binding : if let

func testFuc(optionalStr:String?) {
	if let unwrapStr = optionalStr {
       print(unwrapStr)
    }
}

🤡 Early Exit : guard문

guard 조건값 else {	
	//조건값이 거짓일때 실행
}
func getFriendList(list:[String]?) {
	guard let list = list else { return }
	// list가 nil이 아닐 때에만 아래를 실행하라
	for name in list {
		if name == "abcd" {
			print("find")
    	}
    }
 }

Optional Chaining

if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
    print("The star image is in PNG format")
}

Using the Nil-Coalescing Operator

let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
print(heartPath)
// Prints "/images/default.png"